﻿// ************************************************* //
// MainForm.cs
// Author: Chris Wu
// Email: cwu@dataio.com
// ------------------------------------ //
// version 1.0 - Initial Create
// date: April 21st, 2010
// ------------------------------------ //
//
// ************************************************* //

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Common;
using System.Diagnostics;
using System.IO;
//using Excel

namespace AdapterTool_Demo
{
    /// <summary>
    /// Description of MainForm --> AdapterTool - Demo.
    /// </summary>
    public partial class MainForm : Form
    {
        // resources assignment
        // *********************************************************** //
        // menuStrip1: Software Menu Strip
        // statusStrip: Software Status Strip Show
        // label1: system mode label
        // dataGridView1: pinout label references
        // dataGridView2: pinout list
        // dataGridView3: pin assignment array
        // textbox1: Adapter ID
        // textbox2: Adapter Name
        // textbox3: Total Pins
        // textbox4: PinMapId
        // textbox5: PackageInfo
        // textbox6: BodySize
        // textbox7: Width
        // textbox8: Pitch
        // textbox9: BallDiameter
        // textbox10: BallHeight
        // textbox11: PkgHeight
        // textbox12: NotesListShow
        // comboBox1: Package selection
        // comboBox2: SocketNum
        // comboBox3: PinOneOri
        // numericUpDown1: RowNum
        // numericUpDown2: ColumnNum
        // checkBox1: HIC
        // radioButton1: Alphabetic Mark
        // radioButton2: Numberical Mark
        // button1: Load Record
        // button2: Save Record
        // button3: Update Record
        // button4: Delete Record
        // button5: CreatePinMap
        // button6: OutputPinMap
        // button7: Search
        // button8: Unlock
        // button9: PadsTemp
        // button 10: AddNotes
        // button11: EditNotes
        // button12: DeleteNotes
        // dataGridView4: NoteList
        // button13: AddImage
        // button14: ShowImage
        // button15: deleteImage
        // dataGridView5: ImageList
        // pictureBox1: ImageShow
        // *********************************************************** //


        public static string[] fbga_alph = {   "A", "B", "C", "D", "E", "F", "G",  // 1 - 7
                                                "H", "J", "K", "L", "M", "N", "P",  // 8 - 14
                                                "R", "T", "U", "V", "W", "Y", "AA", // 15 - 21
                                                "AB", "AC", "AD", "AE", "AF"};      // 22 - 26
        private int m_OperationMode = 0;   // OperationMode, 0 - Define Mode, 1 - Search Mode
        private int m_adptrid;
        private int m_pinmapid;
        private string m_adptrname;
        private int m_totalp;
        private int m_rownum;
        private int m_columnum;
        private bool m_checkhic;
        private string m_pcktype;
        private string m_pckname;
        private string m_socketid;
        //private bool m_alpha_num;       // true - alpha, false - num
        //private string m_pckinfo;
        //private double m_bodysize;
        //private double m_width;
        //private double m_pitch;
        //private double m_balldiameter;
        //private double m_ballheight;
        //private double m_pkgheight;
        //private int m_socketnum;
        //private string m_pinoneori;
        private int m_listsize;
        private string[] m_posilist = null;
        private string[] m_labelist = null;
        private string[] m_devpinlist = null;
        private bool m_viewover;
        private double m_scales;
        private bool m_login;
        private string m_user;
        private int m_privilege;    // 0 - query, 1 - admin, 2 - engineer, -1 - nothing
        private bool m_lock;    // true - lock, false - unlock
        private double mp_totalheight;
        private double mp_singlepage;
        private int mp_pageno;
        //private int 

        // MainForm Constructor
        public MainForm()
        {
            InitializeComponent();

            statusStrip.Text = "Loading ... ";

            // initializations
            m_OperationMode = 0;
            label1.Text = "Define Mode";
            m_adptrid = 0;
            m_pinmapid = 0;
            m_totalp = 0;
            m_rownum = 0;
            m_columnum = 0;
            m_checkhic = false;
            //m_alpha_num = true;
            //radioButton1.Checked = true;
            //m_bodysize = 0.0;
            //m_width = 0.0;
            //m_pitch = 0.0;
            //m_balldiameter = 0.0;
            //m_ballheight = 0.0;
            //m_pkgheight = 0.0;
            //m_socketnum = 4;
            m_listsize = 0;
            m_viewover = false;
            m_login = false;
            m_privilege = -1;
            m_lock = true;

            dataGridView4.RowCount = 0;
            dataGridView5.RowCount = 0;

            int i = 0;
            // initialize dataGridView1
            // redesign as below, 5 x 15
            for (i = 0; i < 15; i++)
            {
                dataGridView1.Columns.Add("column" + i.ToString(), "");
                dataGridView1.Columns[i].Width = 50;
                if (i > 12)
                    dataGridView1.Columns[i].Width = 60;
                dataGridView1.Columns[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                if (i % 2 == 1)
                    dataGridView1.Columns[i].DefaultCellStyle.BackColor = System.Drawing.Color.Cyan;
            }

            dataGridView1.Rows.Add("G1", "CE", "D0", "D4", "A0", "A4", "D8", "D12", "A8", "A12", "A31", "A26", "A21", "CE_NOT", "#1");
            dataGridView1.Rows.Add("G2", "WE", "D1", "D5", "A1", "A5", "D9", "D13", "A9", "A13", "A30", "A25", "A20", "WE_NOT", "#2");
            dataGridView1.Rows.Add("G3", "OE", "D2", "D6", "A2", "A6", "D10", "D14", "A10", "A14", "A29", "A24", "A19", "OE_NOT", "#3");
            dataGridView1.Rows.Add("G4", "RE", "D3", "D7", "A3", "A7", "D11", "D15", "A11", "A15", "A28", "A23", "A18", "RE_NOT", "#4");
            dataGridView1.Rows.Add("VCC", "GND", "NC", "DNU", "NOP", "*", "#1", "**", "***", "A16", "A27", "A22", "A17", "TP_PIN", "VCCQ");
            dataGridView1.Rows[0].Height = 24;
            dataGridView1.Rows[1].Height = 24;
            dataGridView1.Rows[2].Height = 24;
            dataGridView1.Rows[3].Height = 24;
            dataGridView1.Rows[4].Height = 24;

            // give out the default pinout lists
            // prepare dataGridView2
            // first to fix the position for pin map, and then to set the labels
            dataGridView2.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridView2.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridView2.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            //dataGridView2.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridView2.Columns[0].SortMode = DataGridViewColumnSortMode.NotSortable;
            dataGridView2.Columns[1].SortMode = DataGridViewColumnSortMode.NotSortable;
            dataGridView2.Columns[2].SortMode = DataGridViewColumnSortMode.NotSortable;
            //dataGridView2.Columns[3].SortMode = DataGridViewColumnSortMode.NotSortable;
            dataGridView2.Columns[0].ReadOnly = true;

            //LogInForm lif = new LogInForm();
            //if (lif.ShowDialog() != DialogResult.OK)
            //    return;
            //m_login = true;
            //m_privilege = lif.ULTE.Privilege;
            //m_user = lif.ULTE.User;
            //textBox13.Text = m_user;
                        
            statusStrip.Text = "Ready";
        }

        // get the about us MessageBox
        private void aboutUsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("Demo of AdapterTool\n\nVersion: 2010.05.beta\nAuthor: chris\nComp.: Data I/O, China\nEmail: cwu@dataio.com", "About Us");
            MyAboutBox mab = new MyAboutBox();
            mab.Show();
        }

        // exit this software
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //this.Close();
            button16_Click(sender, e);
        }

        // set the software into Define Mode
        private void defineModeCtrlFToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (m_login == false)
            {
                MessageBox.Show("Please log in first!", "Warning");
                return;
            }
            if (m_privilege == 0)
            { 
                // don't have the privilege to define data
                MessageBox.Show("You couldn't define adapter. Please contact the administrator if you need!", "Warning");
                return;
            }
            m_OperationMode = 0;
            label1.Text = "Define Mode";
            label1.BackColor = System.Drawing.Color.Gold;

            statusStrip.Text = "In Define Mode";
        }

        // set the software into Search Mode
        private void searchModeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (m_login == false)
            {
                MessageBox.Show("Please log in first!", "Warning");
                return;
            }
            m_OperationMode = 1;
            label1.Text = "Search Mode";
            label1.BackColor = System.Drawing.Color.Gold;

            statusStrip.Text = "In Search Mode";
        }

        // update m_rownum
        private void numericUpDown1_ValueChanged(object sender, EventArgs e)
        {
            //if (m_lock)
            //{
            //    MessageBox.Show("The record is locked.", "Note");
            //    return;
            //}
            if (m_OperationMode == 0)
            {
                m_rownum = int.Parse(numericUpDown1.Value.ToString());
                if (m_rownum > fbga_alph.Length &&
                    (m_pckname == "BGA" || m_pckname == "LGA"))
                {
                    MessageBox.Show("Alphabetic Mark for BAG/LGA only supports less than 26 numbers.", "Warning");
                    m_rownum = fbga_alph.Length;
                    numericUpDown1.Value = m_rownum;
                }
            }
        }

        // update m_columnnum
        private void numericUpDown2_ValueChanged(object sender, EventArgs e)
        {
            //if (m_lock)
            //{
            //    MessageBox.Show("The record is locked.", "Note");
            //    return;
            //}
            if (m_OperationMode == 0)
            {
                m_columnum = int.Parse(numericUpDown2.Value.ToString());
            }
        }

        // update m_adptrname according to m_adptrid
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            //if (m_OperationMode == 0)
            //{
            //    m_adptrid = int.Parse(textBox1.Text);
            //    if (m_adptrid < 10)
            //        m_adptrname = "PA-" + m_pcktype + "00" + m_adptrid.ToString();
            //    else if (m_adptrid < 100)
            //        m_adptrname = "PA-" + m_pcktype + "0" + m_adptrid.ToString();
            //    else
            //        m_adptrname = "PA-" + m_pcktype + m_adptrid.ToString();

            //    if (m_checkhic)
            //        m_adptrname += "HIC";
                
            //    textBox2.Text = m_adptrname;
            //}
        }

        // update m_adptrname according to m_checkhic
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            //m_checkhic = checkBox1.Checked;

            //if (m_OperationMode == 0)
            //{
            //    //m_adptrid = int.Parse(textBox1.Text);
            //    if (m_adptrid < 10)
            //        m_adptrname = "PA-" + m_pcktype + "00" + m_adptrid.ToString();
            //    else if (m_adptrid < 100)
            //        m_adptrname = "PA-" + m_pcktype + "0" + m_adptrid.ToString();
            //    else
            //        m_adptrname = "PA-" + m_pcktype + m_adptrid.ToString();

            //    if (m_checkhic)
            //        m_adptrname += "HIC";

            //    textBox2.Text = m_adptrname;
            //}
        }

        // select package type changed
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (m_lock)
            //{
            //    MessageBox.Show("The record is locked.", "Note");
            //    return;
            //}
            if (m_OperationMode == 0)
            {
                m_pckname = comboBox1.Text;
                switch (m_pckname)
                {
                    case "DIP":
                        m_pcktype = "D";
                        break;
                    case "BGA":
                        m_pcktype = "G";
                        // check the alphabetic mark
                        if (m_rownum > fbga_alph.Length)
                        {
                            m_rownum = fbga_alph.Length;
                            numericUpDown1.Value = m_rownum;
                        }
                        break;
                    case "LGA":
                        if (m_rownum > fbga_alph.Length)
                        {
                            m_rownum = fbga_alph.Length;
                            numericUpDown1.Value = m_rownum;
                        }
                        m_pcktype = "L";
                        break;
                    case "QFN":
                        m_pcktype = "L";
                        break;
                    case "QFP":
                        m_pcktype = "Q";
                        break;
                    case "SOIC":
                        m_pcktype = "S";
                        break;
                    case "TSOP":
                        m_pcktype = "T";
                        break;
                    case "PLCC":
                        m_pcktype = "P";
                        break;
                }
                if (m_adptrid < 10)
                    m_adptrname = "PA-" + m_pcktype + "00" + m_adptrid.ToString();
                else if (m_adptrid < 100)
                    m_adptrname = "PA-" + m_pcktype + "0" + m_adptrid.ToString();
                else
                    m_adptrname = "PA-" + m_pcktype + m_adptrid.ToString();
                
                if (m_checkhic)
                    m_adptrname += "HIC";

                //textBox2.Text = m_adptrname;
            }

            statusStrip.Text = "Package is " + comboBox1.Text;
        }

        // select alphabetic
        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            //m_alpha_num = true;
        }

        // select numerical
        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            //m_alpha_num = false;
        }

        // create Pin Map under Define Mode
        private void createPinMapToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (m_login == false)
            {
                MessageBox.Show("Please log in first!", "Warning");
                return;
            }
            if (m_OperationMode == 1)
            {
                // if in Search Mode, return;
                MessageBox.Show("You can only create pinmap under Define Mode.", "Warning");
                return;
            }

            statusStrip.Text = "Create PinMap";

            switch (m_pckname)
            {
                case "BGA":
                case "LGA":
                    // create BGA_LGAAdapter
                    BGA_LGAAdapter blgaadptr = new BGA_LGAAdapter();
                    blgaadptr.PinMapId = m_pinmapid;
                    blgaadptr.RowNum = m_rownum;
                    blgaadptr.ColumnNum = m_columnum;

                    m_listsize = m_rownum * m_columnum;
                    m_posilist = blgaadptr.PositionList;
                    m_labelist = blgaadptr.LabelList;

                    //radioButton1.Checked = true;
                    //m_alpha_num = true;
                    break;
                case "DIP":
                case "SOIC":
                case "TSOP":
                    //create DIP_TSOP_SOICAdapter
                    DIP_TSOP_SOICAdapter dtsadptr = new DIP_TSOP_SOICAdapter();
                    dtsadptr.PinMapId = m_pinmapid;
                    dtsadptr.RowNum = m_rownum;
                    m_columnum = 2;
                    numericUpDown2.Value = m_columnum;

                    m_listsize = m_rownum * 2;
                    m_posilist = dtsadptr.PositionList;
                    m_labelist = dtsadptr.LabelList;

                    //radioButton2.Checked = true;
                    //m_alpha_num = false;
                    break;
                case "QFP":
                case "PLCC":
                    // create QFPAdatper
                    QFP_PLCCAdapter qpadptr = new QFP_PLCCAdapter();
                    qpadptr.PinMapId = m_pinmapid;
                    qpadptr.RowNum = m_rownum;
                    qpadptr.ColumnNum = m_columnum;

                    m_listsize = (m_rownum + m_columnum) * 2;
                    m_posilist = qpadptr.PositionList;
                    m_labelist = qpadptr.LabelList;

                    //radioButton2.Checked = true;
                    //m_alpha_num = false;
                    break;
                case "QFN":
                    // create QFNAdapter
                    QFNAdapter qnadptr = new QFNAdapter();
                    qnadptr.PinMapId = m_pinmapid;
                    qnadptr.RowNum = m_rownum;
                    qnadptr.ColumnNum = m_columnum;

                    m_listsize = (m_rownum + m_columnum) * 2 + 1;
                    m_posilist = qnadptr.PositionList;
                    m_labelist = qnadptr.LabelList;

                    //radioButton2.Checked = true;
                    //m_alpha_num = false;
                    break;
            }
            m_devpinlist = new string[m_listsize];
            for (int k = 0; k < m_listsize; k++)
            {
                m_devpinlist[k] = "";
            }

            m_totalp = 0;
            textBox3.Text = m_totalp.ToString();

            // fill dataGridView2, pinout list
            dataGridView2.RowCount = 0;
            int i, j;
            for (i = 0; i < m_listsize; i++)
            {
                dataGridView2.Rows.Add(m_posilist[i]);
                if (i % 2 == 0)
                {
                    dataGridView2[0, i].Style.BackColor = System.Drawing.Color.Pink;
                }
            }

            // draw dataGridView3, pin assignmeng array
            dataGridView3.RowCount = 0;
            dataGridView3.ColumnCount = 0;
            dataGridView3.Font = new Font("微软雅黑", 8, FontStyle.Bold);  ;
            switch (m_pckname)
            {
                case "DIP":
                case "SOIC":
                case "TSOP":
                    for (i = 0; i < m_columnum + 5; i++)
                    {
                        dataGridView3.Columns.Add("column" + i.ToString(), "");
                        dataGridView3.Columns[i].Width = 50;
                        dataGridView3.Columns[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                    }

                    for (i = 0; i < m_rownum; i++)
                    {
                        dataGridView3.Rows.Add();
                    }

                    for (i = 0; i < m_rownum; i++)
                    {
                        dataGridView3[1, i].Value = (i + 1).ToString();
                        dataGridView3[5, i].Value = (2 * m_rownum - i).ToString();
                        dataGridView3.Rows[i].Height = 50;
                    }
                    dataGridView3.Columns[1].DefaultCellStyle.BackColor = System.Drawing.Color.Pink;
                    dataGridView3.Columns[5].DefaultCellStyle.BackColor = System.Drawing.Color.Pink;
                    dataGridView3.Columns[3].DefaultCellStyle.BackColor = System.Drawing.Color.Gray;
                    dataGridView3.Columns[2].DefaultCellStyle.BackColor = System.Drawing.Color.LightGray;
                    dataGridView3.Columns[4].DefaultCellStyle.BackColor = System.Drawing.Color.LightGray;
                    dataGridView3.Columns[1].Width = 30;
                    dataGridView3.Columns[5].Width = 30;
                    dataGridView3.Columns[2].Width = 40;
                    dataGridView3.Columns[4].Width = 40;
                    dataGridView3.Columns[3].Width = 100;
                    break;
                case "BGA":
                case "LGA":
                    for (i = 0; i <= m_columnum; i++)
                    {
                        dataGridView3.Columns.Add("column" + i, "");
                        dataGridView3.Columns[i].Width = 50;
                        dataGridView3.Columns[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                    }
                    for (i = 0; i <= m_rownum; i++)
                    {
                        dataGridView3.Rows.Add();
                    }
                    dataGridView3[0, 0].Style.BackColor = System.Drawing.Color.Gray;
                    for (i = 1; i <= m_columnum; i++)
                    {
                        dataGridView3[i, 0].Value = i.ToString();
                        dataGridView3[i, 0].Style.BackColor = System.Drawing.Color.Pink;
                    }
                    for (i = 1; i <= m_rownum; i++)
                    {
                        dataGridView3[0, i].Value = fbga_alph[i - 1];
                        dataGridView3[0, i].Style.BackColor = System.Drawing.Color.Pink;
                        dataGridView3.Rows[i].Height = 50;
                    }
                    dataGridView3.Rows[0].Height = 20;
                    dataGridView3.Columns[0].Width = 30;
                    break;
                case "QFP":
                case "PLCC":
                    // create a circle
                    for (i = 0; i < m_columnum + 6; i++)
                    {
                        dataGridView3.Columns.Add("column" + i.ToString(), "");
                        dataGridView3.Columns[i].Width = 50;
                        dataGridView3.Columns[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                    }

                    for (i = 0; i < m_rownum + 6; i++)
                    {
                        dataGridView3.Rows.Add();
                    }

                    for (i = 4; i < m_rownum + 4; i++)
                    {
                        dataGridView3[1, i - 1].Value = (i - 3).ToString();
                        dataGridView3[m_columnum + 4, i - 1].Value = (2 * m_rownum + m_columnum + 4 - i).ToString();
                        dataGridView3[1, i - 1].Style.BackColor = System.Drawing.Color.Pink;
                        dataGridView3[m_columnum + 4, i - 1].Style.BackColor = System.Drawing.Color.Pink;
                        dataGridView3.Rows[i - 1].Height = 50;
                    }

                    dataGridView3.Columns[2].DefaultCellStyle.BackColor = System.Drawing.Color.LightGray;
                    dataGridView3.Columns[m_columnum + 3].DefaultCellStyle.BackColor = System.Drawing.Color.LightGray;
                    dataGridView3.Rows[2].DefaultCellStyle.BackColor = System.Drawing.Color.LightGray;
                    dataGridView3.Rows[m_rownum + 3].DefaultCellStyle.BackColor = System.Drawing.Color.LightGray;

                    for (i = 0; i < 3; i++)
                    {
                        dataGridView3[m_columnum + 3, i].Style.BackColor = System.Drawing.Color.Gray;
                        dataGridView3[m_columnum + 4, i].Style.BackColor = System.Drawing.Color.Gray;
                        dataGridView3[m_columnum + 5, i].Style.BackColor = System.Drawing.Color.Gray;

                        dataGridView3[0, i].Style.BackColor = System.Drawing.Color.Gray;
                        dataGridView3[1, i].Style.BackColor = System.Drawing.Color.Gray;
                        dataGridView3[2, i].Style.BackColor = System.Drawing.Color.Gray;

                        dataGridView3[i, m_rownum + 3].Style.BackColor = System.Drawing.Color.Gray;
                        dataGridView3[i, m_rownum + 4].Style.BackColor = System.Drawing.Color.Gray;
                        dataGridView3[i, m_rownum + 5].Style.BackColor = System.Drawing.Color.Gray;

                        dataGridView3[m_columnum + 3 + i, m_rownum + 3].Style.BackColor = System.Drawing.Color.Gray;
                        dataGridView3[m_columnum + 3 + i, m_rownum + 4].Style.BackColor = System.Drawing.Color.Gray;
                        dataGridView3[m_columnum + 3 + i, m_rownum + 5].Style.BackColor = System.Drawing.Color.Gray;

                    }
                    dataGridView3.Rows[0].Height = 50;
                    dataGridView3.Rows[1].Height = 30;
                    dataGridView3.Rows[2].Height = 40;
                    dataGridView3.Rows[m_rownum + 3].Height = 40;
                    dataGridView3.Rows[m_rownum + 4].Height = 30;
                    dataGridView3.Rows[m_rownum + 5].Height = 50;

                    for (i = 3; i < m_columnum + 3; i++)
                    {
                        dataGridView3[i, m_rownum + 4].Value = (m_rownum + i - 2).ToString();
                        dataGridView3[i, m_rownum + 4].Style.BackColor = System.Drawing.Color.Pink;
                        dataGridView3[i, 1].Value = (2 * m_rownum + 2 * m_columnum + 3 - i).ToString();
                        dataGridView3[i, 1].Style.BackColor = System.Drawing.Color.Pink;
                        for (j = 3; j < m_rownum + 3; j++)
                        {
                            dataGridView3[i, j].Style.BackColor = System.Drawing.Color.Gray;
                        }
                    }
                    dataGridView3.Columns[0].Width = 50;
                    dataGridView3.Columns[1].Width = 30;
                    dataGridView3.Columns[2].Width = 40;
                    dataGridView3.Columns[m_columnum + 3].Width = 40;
                    dataGridView3.Columns[m_columnum + 4].Width = 30;
                    dataGridView3.Columns[m_columnum + 5].Width = 50;
                    break;
                case "QFN":
                    // create a circle, plus a center point
                    for (i = 0; i < m_columnum + 6; i++)
                    {
                        dataGridView3.Columns.Add("column" + i.ToString(), "");
                        dataGridView3.Columns[i].Width = 50;
                        dataGridView3.Columns[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                    }

                    for (i = 0; i < m_rownum + 6; i++)
                    {
                        dataGridView3.Rows.Add();
                    }

                    for (i = 4; i < m_rownum + 4; i++)
                    {
                        dataGridView3[1, i - 1].Value = (i - 3).ToString();
                        dataGridView3[m_columnum + 4, i - 1].Value = (2 * m_rownum + m_columnum + 4 - i).ToString();
                        dataGridView3[1, i - 1].Style.BackColor = System.Drawing.Color.Pink;
                        dataGridView3[m_columnum + 4, i - 1].Style.BackColor = System.Drawing.Color.Pink;
                        dataGridView3.Rows[i - 1].Height = 50;
                    }

                    dataGridView3.Columns[2].DefaultCellStyle.BackColor = System.Drawing.Color.LightGray;
                    dataGridView3.Columns[m_columnum + 3].DefaultCellStyle.BackColor = System.Drawing.Color.LightGray;
                    dataGridView3.Rows[2].DefaultCellStyle.BackColor = System.Drawing.Color.LightGray;
                    dataGridView3.Rows[m_rownum + 3].DefaultCellStyle.BackColor = System.Drawing.Color.LightGray;

                    for (i = 0; i < 3; i++)
                    {
                        dataGridView3[m_columnum + 3, i].Style.BackColor = System.Drawing.Color.Gray;
                        dataGridView3[m_columnum + 4, i].Style.BackColor = System.Drawing.Color.Gray;
                        dataGridView3[m_columnum + 5, i].Style.BackColor = System.Drawing.Color.Gray;

                        dataGridView3[0, i].Style.BackColor = System.Drawing.Color.Gray;
                        dataGridView3[1, i].Style.BackColor = System.Drawing.Color.Gray;
                        dataGridView3[2, i].Style.BackColor = System.Drawing.Color.Gray;

                        dataGridView3[i, m_rownum + 3].Style.BackColor = System.Drawing.Color.Gray;
                        dataGridView3[i, m_rownum + 4].Style.BackColor = System.Drawing.Color.Gray;
                        dataGridView3[i, m_rownum + 5].Style.BackColor = System.Drawing.Color.Gray;

                        dataGridView3[m_columnum + 3 + i, m_rownum + 3].Style.BackColor = System.Drawing.Color.Gray;
                        dataGridView3[m_columnum + 3 + i, m_rownum + 4].Style.BackColor = System.Drawing.Color.Gray;
                        dataGridView3[m_columnum + 3 + i, m_rownum + 5].Style.BackColor = System.Drawing.Color.Gray;

                    }
                    dataGridView3.Rows[0].Height = 50;
                    dataGridView3.Rows[1].Height = 30;
                    dataGridView3.Rows[2].Height = 40;
                    dataGridView3.Rows[m_rownum + 3].Height = 40;
                    dataGridView3.Rows[m_rownum + 4].Height = 30;
                    dataGridView3.Rows[m_rownum + 5].Height = 50;

                    for (i = 3; i < m_columnum + 3; i++)
                    {
                        dataGridView3[i, m_rownum + 4].Value = (m_rownum + i - 2).ToString();
                        dataGridView3[i, m_rownum + 4].Style.BackColor = System.Drawing.Color.Pink;
                        dataGridView3[i, 1].Value = (2 * m_rownum + 2 * m_columnum + 3 - i).ToString();
                        dataGridView3[i, 1].Style.BackColor = System.Drawing.Color.Pink;
                        for (j = 3; j < m_rownum + 3; j++)
                        {
                            dataGridView3[i, j].Style.BackColor = System.Drawing.Color.Gray;
                        }
                    }
                    dataGridView3.Columns[0].Width = 50;
                    dataGridView3.Columns[1].Width = 30;
                    dataGridView3.Columns[2].Width = 40;
                    dataGridView3.Columns[m_columnum + 3].Width = 40;
                    dataGridView3.Columns[m_columnum + 4].Width = 30;
                    dataGridView3.Columns[m_columnum + 5].Width = 50;

                    dataGridView3[3 + m_columnum / 2, 3 + m_rownum / 2].Style.BackColor = System.Drawing.Color.White;
                    break;
            }

            statusStrip.Text = "Ready";
        }

        // create Pin Map under Define Mode
        private void button5_Click(object sender, EventArgs e)
        {
            createPinMapToolStripMenuItem_Click(sender, e);
        }

        // get row and column for DIP_SOIC_TSOP adapter
        private void getRowColumn_DIP_SOIC_TSOP(int loc, ref int myrr, ref int mycc, bool label_devpin)
        {
            myrr = 0;
            mycc = 0;

            if (label_devpin)
            {   // for labels
                if (loc <= m_rownum)
                {
                    myrr = loc - 1;
                    mycc = 0;
                }
                else
                {
                    myrr = 2 * m_rownum - loc;
                    mycc = 6;
                }
            }
            else
            {   // for devpins
                if (loc <= m_rownum)
                {
                    mycc = 2;
                    myrr = loc - 1;
                }
                else
                {
                    mycc = 4;
                    myrr = 2 * m_rownum - loc;
                }
            }

            return;
        }

        // get row and column for QFP_PLCC adapter
        private void getRowColumn_QFP_PLCC(int loc, ref int myrr, ref int mycc, bool label_devpin)
        {
            myrr = 0;
            mycc = 0;

            if (label_devpin)
            {   // for labels
                if (loc <= m_rownum)
                {
                    myrr = loc + 2;
                    mycc = 0;
                }
                else if (loc <= (m_rownum + m_columnum))
                {
                    mycc = loc - m_rownum + 2;
                    myrr = m_rownum + 5;
                }
                else if (loc <= (2 * m_rownum + m_columnum))
                {
                    mycc = m_columnum + 5;
                    myrr = (2 * m_rownum + m_columnum) - loc + 3;
                }
                else
                {
                    myrr = 0;
                    mycc = (2 * m_rownum + 2 * m_columnum) - loc + 3;
                }
            }
            else
            {   // for devpins
                if (loc <= m_rownum)
                {
                    myrr = loc + 2;
                    mycc = 2;
                }
                else if (loc <= (m_rownum + m_columnum))
                {
                    mycc = loc - m_rownum + 2;
                    myrr = m_rownum + 3;
                }
                else if (loc <= (2 * m_rownum + m_columnum))
                {
                    mycc = m_columnum + 3;
                    myrr = (2 * m_rownum + m_columnum) - loc + 3;
                }
                else
                {
                    myrr = 2;
                    mycc = (2 * m_rownum + 2 * m_columnum) - loc + 3;
                }
            }

                return;
        }

        // get row and column for QFN adapter
        private void getRowColumn_QFN(int loc, ref int myrr, ref int mycc, bool label_devpin)
        {
            myrr = 0;
            mycc = 0;

            if (label_devpin)
            {   // for labels
                if (loc <= m_rownum)
                {
                    myrr = loc + 2;
                    mycc = 0;
                }
                else if (loc <= (m_rownum + m_columnum))
                {
                    mycc = loc - m_rownum + 2;
                    myrr = m_rownum + 5;
                }
                else if (loc <= (2 * m_rownum + m_columnum))
                {
                    mycc = m_columnum + 5;
                    myrr = (2 * m_rownum + m_columnum) - loc + 3;
                }
                else if (loc <= (2 * m_rownum + 2 * m_columnum))
                {
                    myrr = 0;
                    mycc = (2 * m_rownum + 2 * m_columnum) - loc + 3;
                }
                else
                {
                    myrr = 3 + m_rownum / 2;
                    mycc = 3 + m_columnum / 2;
                }
            }
            else
            {   // for devpins
                if (loc <= m_rownum)
                {
                    myrr = loc + 2;
                    mycc = 2;
                }
                else if (loc <= (m_rownum + m_columnum))
                {
                    mycc = loc - m_rownum + 2;
                    myrr = m_rownum + 3;
                }
                else if (loc <= (2 * m_rownum + m_columnum))
                {
                    mycc = m_columnum + 3;
                    myrr = (2 * m_rownum + m_columnum) - loc + 3;
                }
                else if (loc <= (2 * m_rownum + 2 * m_columnum))
                {
                    myrr = 2;
                    mycc = (2 * m_rownum + 2 * m_columnum) - loc + 3;
                }
                else
                {
                    return;
                }
            }

            return;
        }

        // modify the pinout list manually
        private void dataGridView2_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (m_lock)
            {
                MessageBox.Show("The record is locked.", "Note");
                dataGridView2.ReadOnly = true;
                return;
            }
            dataGridView2.ReadOnly = false;
            if (3 == dataGridView2.CurrentCell.ColumnIndex)               
            {
                return;
            }
            if (null == dataGridView2.CurrentCell.Value)
            {
                dataGridView2.CurrentCell.Value = "";
            }
            statusStrip.Text = "Define Adapter";

            int mycc = 0, myrr = 0; // position in dataGridView3
            bool bfill = true;
            bool blabel_devpin = true;
            if (1 == dataGridView2.CurrentCell.ColumnIndex)
            {   // update the Label Column                
                switch (m_pckname)
                {
                    case "DIP":
                    case "SOIC":
                    case "TSOP":
                        int tmp1 = dataGridView2.CurrentCell.RowIndex + 1;
                        getRowColumn_DIP_SOIC_TSOP(tmp1, ref myrr, ref mycc, true);
                        break;
                    case "BGA":
                    case "LGA":
                        myrr = dataGridView2.CurrentCell.RowIndex / m_columnum + 1;
                        mycc = dataGridView2.CurrentCell.RowIndex % m_columnum + 1;
                        break;
                    case "QFP":
                    case "PLCC":
                        int tmp2 = dataGridView2.CurrentCell.RowIndex + 1;
                        getRowColumn_QFP_PLCC(tmp2, ref myrr, ref mycc, true);
                        break;
                    case "QFN":
                        int tmp3 = dataGridView2.CurrentCell.RowIndex + 1;
                        getRowColumn_QFN(tmp3, ref myrr, ref mycc, true);
                        break;
                }
            }
            else if (2 == dataGridView2.CurrentCell.ColumnIndex)
            {   // update the DevicePin Column
                switch (m_pckname)
                {
                    case "DIP":
                    case "SOIC":
                    case "TSOP":
                        int tmp4 = dataGridView2.CurrentCell.RowIndex + 1;
                        getRowColumn_DIP_SOIC_TSOP(tmp4, ref myrr, ref mycc, false);
                        break;
                    case "BGA":
                    case "LGA":
                        bfill = false;
                        break;
                    case "QFP":
                    case "PLCC":
                        int tmp5 = dataGridView2.CurrentCell.RowIndex + 1;
                        getRowColumn_QFP_PLCC(tmp5, ref myrr, ref mycc, false);
                        break;
                    case "QFN":
                        int tmp6 = dataGridView2.CurrentCell.RowIndex + 1;
                        getRowColumn_QFN(tmp6, ref myrr, ref mycc, false);
                        if (0 == mycc && 0 == myrr)
                        {
                            bfill = false;
                        }
                        break;
                }
                blabel_devpin = false;
                m_devpinlist[dataGridView2.CurrentCell.RowIndex] = dataGridView2.CurrentCell.Value.ToString();
            }
            if (bfill)
            {
                // fill dataGridView3
                if (1 == dataGridView2.CurrentCell.ColumnIndex)
                    m_labelist[dataGridView2.CurrentCell.RowIndex] = dataGridView2.CurrentCell.Value.ToString();
                
                dataGridView3[mycc, myrr].Value = dataGridView2.CurrentCell.Value;
                dataGridView3.CurrentCell = dataGridView3[mycc, myrr];  // bring it to the top
                SetColorRules(dataGridView3[mycc, myrr].Value.ToString(), myrr, mycc, blabel_devpin);                
            }
            // re-calculate totalpins
            recalc_totalpins();
        }

        // re-calculate total pins
        private void recalc_totalpins()
        {
            // calcultate the total pin numbers
            int sum = 0;
            for (int i = 0; i < m_listsize; i++)
            {
                if ("" != m_labelist[i] &&
                    "NOP" != m_labelist[i])
                {
                    sum++;
                }
            }
            m_totalp = sum;
            textBox3.Text = sum.ToString();

            statusStrip.Text = "Total Pins Defnied is " + sum.ToString();
        }

        // begin edit of dataGridView2
        private void dataGridView2_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (m_lock)
            {
                MessageBox.Show("The record is locked.", "Note");
                dataGridView2.ReadOnly = true;
                return;
            }
        }

        // align back pinmap
        private void AlignBackPinMap(string pckname, int myrr, int mycc, bool fill_clear)
        { 
            // myrr, mycc: rownum and columnnum in dataGridView3
            // fill_clear: true - fill, false - clear

            int temp = 0;
            string backupstr = "";
            if (true == fill_clear && null != dataGridView3[mycc, myrr].Value)
            {
                backupstr = dataGridView3[mycc, myrr].Value.ToString();
            }

            switch (pckname)
            {
                case "DIP":
                case "SOIC":
                case "TSOP":
                    // validation
                    if ((0 == mycc && 0 <= myrr && m_rownum > myrr) ||
                        (6 == mycc && 0 <= myrr && m_rownum > myrr))
                    {
                        if (fill_clear)
                        {
                            if (0 < backupstr.Length)
                            {
                                dataGridView3[mycc, myrr].Value = backupstr + "/" + dataGridView1.CurrentCell.Value;
                            }
                            else
                            {
                                dataGridView3[mycc, myrr].Value = dataGridView1.CurrentCell.Value;
                            }

                            SetColorRules(dataGridView3[mycc, myrr].Value.ToString(), myrr, mycc, true);
                        }
                        else
                        {
                            dataGridView3[mycc, myrr].Value = "";
                            dataGridView3[mycc, myrr].Style.BackColor = System.Drawing.Color.White;
                        }

                        // update dataGridView2
                        if (0 == mycc)
                        {
                            temp = myrr + 1;
                        }
                        else if (6 == mycc)
                        {
                            temp = 2 * m_rownum - myrr;
                        }
                        dataGridView2[1, temp - 1].Value = dataGridView3[mycc, myrr].Value;
                        dataGridView2.CurrentCell = dataGridView2[1, temp - 1];
                        m_labelist[temp - 1] = dataGridView3[mycc, myrr].Value.ToString();
                    }
                    break;
                case "BGA":
                case "LGA":
                    // validation
                    if (0 == myrr || 0 == mycc)
                    {
                        break;
                    }

                    if (fill_clear)
                    {
                        if (0 < backupstr.Length)
                        {
                            dataGridView3[mycc, myrr].Value = backupstr + "/" + dataGridView1.CurrentCell.Value;
                        }
                        else
                        {
                            dataGridView3[mycc, myrr].Value = dataGridView1.CurrentCell.Value;
                        }

                        SetColorRules(dataGridView3[mycc, myrr].Value.ToString(), myrr, mycc, true);
                    }
                    else
                    {
                        dataGridView3[mycc, myrr].Value = "";
                        dataGridView3[mycc, myrr].Style.BackColor = System.Drawing.Color.White;
                    }

                    // update dataGridView2
                    temp = (myrr - 1) * m_columnum + (mycc - 1);
                    dataGridView2[1, temp].Value = dataGridView3[mycc, myrr].Value;
                    dataGridView2.CurrentCell = dataGridView2[1, temp];
                    m_labelist[temp] = dataGridView3[mycc, myrr].Value.ToString();
                    break;
                case "QFP":
                case "PLCC":
                    // validation
                    if ((0 == myrr && 2 < mycc && 3 + m_columnum > mycc) ||
                        (5 + m_rownum == myrr && 2 < mycc && 3 + m_columnum > mycc) ||
                        (2 < myrr && 3 + m_rownum > myrr && 0 == mycc) ||
                        (2 < myrr && 3 + m_rownum > myrr && 5 + m_columnum == mycc))
                    {
                        if (fill_clear)
                        {
                            if (0 < backupstr.Length)
                            {
                                dataGridView3[mycc, myrr].Value = backupstr + "/" + dataGridView1.CurrentCell.Value;
                            }
                            else
                            {
                                dataGridView3[mycc, myrr].Value = dataGridView1.CurrentCell.Value;
                            }

                            SetColorRules(dataGridView3[mycc, myrr].Value.ToString(), myrr, mycc, true);
                        }
                        else
                        {
                            dataGridView3[mycc, myrr].Value = "";
                            dataGridView3[mycc, myrr].Style.BackColor = System.Drawing.Color.White;
                        }

                        // update dataGridView2
                        if (0 == myrr)
                        {
                            temp = 2 * (m_rownum + m_columnum) - mycc + 3;
                        }
                        else if (5 + m_rownum == myrr)
                        {
                            temp = m_rownum + mycc - 2;
                        }
                        else if (0 == mycc)
                        {
                            temp = myrr - 2;
                        }
                        else if (5 + m_columnum == mycc)
                        {
                            temp = 2 * m_rownum + m_columnum - myrr + 3;
                        }
                        dataGridView2[1, temp - 1].Value = dataGridView3[mycc, myrr].Value;
                        dataGridView2.CurrentCell = dataGridView2[1, temp - 1];
                        m_labelist[temp - 1] = dataGridView3[mycc, myrr].Value.ToString();
                    }
                    break;
                case "QFN":
                    // validation
                    if ((0 == myrr && 2 < mycc && 3 + m_columnum > mycc) ||
                        (5 + m_rownum == myrr && 2 < mycc && 3 + m_columnum > mycc) ||
                        (2 < myrr && 3 + m_rownum > myrr && 0 == mycc) ||
                        (2 < myrr && 3 + m_rownum > myrr && 5 + m_columnum == mycc) ||
                        (myrr == 3 + m_rownum / 2 && mycc == 3 + m_columnum / 2))
                    {
                        if (fill_clear)
                        {
                            if (0 < backupstr.Length)
                            {
                                dataGridView3[mycc, myrr].Value = backupstr + "/" + dataGridView1.CurrentCell.Value;
                            }
                            else
                            {
                                dataGridView3[mycc, myrr].Value = dataGridView1.CurrentCell.Value;
                            }

                            SetColorRules(dataGridView3[mycc, myrr].Value.ToString(), myrr, mycc, true);
                        }
                        else
                        {
                            dataGridView3[mycc, myrr].Value = "";
                            dataGridView3[mycc, myrr].Style.BackColor = System.Drawing.Color.White;
                        }

                        // update dataGridView2
                        if (0 == myrr)
                        {
                            temp = 2 * (m_rownum + m_columnum) - mycc + 3;
                        }
                        else if (5 + m_rownum == myrr)
                        {
                            temp = m_rownum + mycc - 2;
                        }
                        else if (0 == mycc)
                        {
                            temp = myrr - 2;
                        }
                        else if (5 + m_columnum == mycc)
                        {
                            temp = 2 * m_rownum + m_columnum - myrr + 3;
                        }
                        else
                            temp = 2 * m_columnum + 2 * m_rownum + 1;
                        dataGridView2[1, temp - 1].Value = dataGridView3[mycc, myrr].Value;
                        dataGridView2.CurrentCell = dataGridView2[1, temp - 1];
                        m_labelist[temp - 1] = dataGridView3[mycc, myrr].Value.ToString();
                    }
                    break;
            }
        }

        // modify the pin assignment array
        private void dataGridView3_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (m_lock)
            {
                MessageBox.Show("The record is locked.", "Note");
                return;
            }
            int myrr, mycc;
            myrr = dataGridView3.CurrentCell.RowIndex;
            mycc = dataGridView3.CurrentCell.ColumnIndex;

            AlignBackPinMap(m_pckname, myrr, mycc, true);
            recalc_totalpins();
        }

        // set multiple cells using right mouse key
        private void dataGridView3_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                rightMenuStrip.Show(MousePosition.X, MousePosition.Y);
            }

        }

        // fill with rightMenuStrip
        private void fillToolStripMenuItem_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < dataGridView3.RowCount; i++)
            {
                for (int j = 0; j < dataGridView3.ColumnCount; j++)
                {
                    if (dataGridView3[j, i].Selected)
                    {
                        AlignBackPinMap(m_pckname, i, j, true);
                        recalc_totalpins();
                    }
                }
            }
        }

        // clear with rightMenuStrip
        private void clearToolStripMenuItem_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < dataGridView3.RowCount; i++)
            {
                for (int j = 0; j < dataGridView3.ColumnCount; j++)
                {
                    if (dataGridView3[j, i].Selected)
                    {
                        AlignBackPinMap(m_pckname, i, j, false);
                        recalc_totalpins();
                    }
                }
            }
        }

        // output the parameter files
        private void outputPinMapToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (m_login == false)
            {
                MessageBox.Show("Please log in first!", "Warning");
                return;
            }
            if (m_OperationMode == 1)
            {
                // if in Search Mode, return;
                MessageBox.Show("You can only do this under Define Mode.", "Warning");
                return;
            }
            FilesOperator filefp = new FilesOperator();
            filefp.AdapterId = m_adptrid;
            filefp.AdapterName = m_adptrname;
            filefp.ColumnNum = m_columnum;
            filefp.LabelList = m_labelist;
            filefp.ListSize = m_listsize;
            filefp.PackageName = m_pckname;
            filefp.PositionList = m_posilist;
            filefp.RowNum = m_rownum;
            filefp.TotalPins = m_totalp;

            filefp.OutputParamFiles();

            return;
        }

        // output the parameter files, button
        private void button6_Click(object sender, EventArgs e)
        {
            outputPinMapToolStripMenuItem_Click(sender, e);
        }

        // open my defined *.pin files
        private void openpinToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (m_login == false)
            {
                MessageBox.Show("Please log in first!", "Warning");
                return;
            }
            if (m_OperationMode == 1)
            {
                // if in Search Mode, return;
                MessageBox.Show("You can only do this under Define Mode.", "Warning");
                return;
            }
            FilesOperator filefp = new FilesOperator();
            filefp.LoadPinFiles();
            m_adptrid = filefp.AdapterId;
            m_adptrname = filefp.AdapterName;
            m_columnum = filefp.ColumnNum;
            m_rownum = filefp.RowNum;
            m_pckname = filefp.PackageName;

            //textBox1.Text = m_adptrid.ToString();
            numericUpDown1.Value = m_rownum;
            numericUpDown2.Value = m_columnum;
            comboBox1.Text = m_pckname;

            // put in data into dataGridView2
            createPinMapToolStripMenuItem_Click(sender, e);

            m_labelist = filefp.LabelList;
            m_totalp = filefp.TotalPins;
            m_listsize = filefp.ListSize;
            textBox3.Text = m_totalp.ToString();

            dataGridView2.ColumnCount = 3;
            dataGridView2.RowCount = m_listsize;
            for (int i = 0; i < m_listsize; i++)
            {
                if ("" != m_labelist[i])
                {
                    dataGridView2[1, i].Value = m_labelist[i];
                }
            }
            AlignPinMap();

            return;
        }

        // save as my defined *.pin files
        private void savepinToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (m_login == false)
            {
                MessageBox.Show("Please log in first!", "Warning");
                return;
            }
            if (m_OperationMode == 1)
            {
                // if in Search Mode, return;
                MessageBox.Show("You can only do this under Define Mode.", "Warning");
                return;
            }
            FilesOperator filefp = new FilesOperator();
            filefp.AdapterId = m_adptrid;
            filefp.AdapterName = m_adptrname;
            filefp.ColumnNum = m_columnum;
            filefp.LabelList = m_labelist;
            filefp.ListSize = m_listsize;
            filefp.PackageName = m_pckname;
            filefp.PositionList = m_posilist;
            filefp.RowNum = m_rownum;
            filefp.TotalPins = m_totalp;

            filefp.SaveAsPinFiles();

            return;
        }

        // align dataGridView2 and dataGridView3 when open *.pin file
        private void AlignPinMap()
        {
            int myrr = 0, mycc = 0;
            for (int i = 0; i < m_listsize; i++)
            {
                if ("" != m_labelist[i])
                {
                    switch (m_pckname)
                    {
                        case "DIP":
                        case "SOIC":
                        case "TSOP":
                            int tmp1 = i + 1;
                            getRowColumn_DIP_SOIC_TSOP(tmp1, ref myrr, ref mycc, true);
                            break;
                        case "BGA":
                        case "LGA":
                            myrr = i / m_columnum + 1;
                            mycc = i % m_columnum + 1;
                            break;
                        case "QFP":
                        case "PLCC":
                            int tmp2 = i + 1;
                            getRowColumn_QFP_PLCC(tmp2, ref myrr, ref mycc, true);
                            break;
                        case "QFN":
                            int tmp3 = i + 1;
                            getRowColumn_QFN(tmp3, ref myrr, ref mycc, true);
                            break;
                    }

                    dataGridView3[mycc, myrr].Value = m_labelist[i];
                    if ("NC" != m_labelist[i])
                    {
                        SetColorRules(m_labelist[i], myrr, mycc, true);
                    }
                }

                if ("" != m_devpinlist[i])
                {
                    switch (m_pckname)
                    { 
                        case "DIP":
                        case "SOIC":
                        case "TSOP":
                            // fill device pins
                            int tmp4 = i + 1;
                            getRowColumn_DIP_SOIC_TSOP(tmp4, ref myrr, ref mycc, false);
                            dataGridView3[mycc, myrr].Value = m_devpinlist[i];
                            break;
                        case "BGA":
                        case "LGA":
                            // do nothing
                            break;
                        case "QFP":
                        case "PLCC":
                            // fill device pins
                            int tmp5 = i + 1;
                            getRowColumn_QFP_PLCC(tmp5, ref myrr, ref mycc, false);
                            dataGridView3[mycc, myrr].Value = m_devpinlist[i];
                            break;
                        case "QFN":
                            // fill device pins
                            if (i < 2 * (m_rownum + m_columnum))
                            {
                                int tmp6 = i + 1;
                                getRowColumn_QFN(tmp6, ref myrr, ref mycc, false);
                                dataGridView3[mycc, myrr].Value = m_devpinlist[i];
                            }
                            break;
                    }
                }
            }

            return;
        }

        // output pads template
        private void padsTempToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (m_login == false)
            {
                MessageBox.Show("Please log in first!", "Warning");
                return;
            }
            FilesOperator filefp = new FilesOperator();
            filefp.AdapterId = m_adptrid;
            filefp.AdapterName = m_adptrname;
            filefp.ColumnNum = m_columnum;
            filefp.LabelList = m_labelist;
            filefp.ListSize = m_listsize;
            filefp.PackageName = m_pckname;
            filefp.PositionList = m_posilist;
            filefp.RowNum = m_rownum;
            filefp.TotalPins = m_totalp;

            filefp.OutputPadTemplate();

            return;
        }

        // save as Excel Files
        private void saveAsxlsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (m_login == false)
            {
                MessageBox.Show("Please log in first!", "Warning");
                return;
            }
            // using stream to export to excel
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Excel files (*.xls) | *.xls";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.Title = "Save as Excel files";
            saveFileDialog.ShowDialog();

            if (saveFileDialog.FileName.IndexOf(":") < 0)
            {   // if click cancel
                return;
            }
            DataGridView[] dgv = new DataGridView[3];
            int num = 0;
            if (dataGridView6.RowCount > 0)
            {
                dgv[num] = new DataGridView();
                dgv[num] = dataGridView6;
                num++;
            }
            if (dataGridView3.RowCount > 0)
            {
                dgv[num] = new DataGridView();
                dgv[num] = dataGridView3;
                num++;
            }
            if (dataGridView4.RowCount > 0)
            {
                dgv[num] = new DataGridView();
                dgv[num] = dataGridView4;
                num++;
            }

            // method 1
            Image temp = Image.FromFile("demo.jpg");
            GetResultIntoImage(ref temp, true);//, dataGridView3);
            //MessageBox.Show("try it.");
            string str = Environment.CurrentDirectory;
            str += "\\test.jpg";
            //MessageBox.Show(str);
            temp.Save(str, System.Drawing.Imaging.ImageFormat.Bmp);
            temp.Dispose();
            //MessageBox.Show("try it again.");
            InsertPicToExcel ipt = new InsertPicToExcel();
            ipt.Open();
            //Bitmap myPic = (Bitmap)dataGridView1[1, 0].Value;
            //myPic.Save(@"D:\test.bmp");
            ipt.InsertDGV(dgv, num);
            ipt.InsertPicture("A1", str);//"C:\\test.bmp");
            //ipt.InsertPicture("B2", (Image)dataGridView1[1, 0]);
            ipt.SaveFile(saveFileDialog.FileName);
            ipt.Dispose();
            MessageBox.Show("Please check " + saveFileDialog.FileName + "!", "Informer");
            return;

            // method 2
            // move the dataGridView3 to excel
            int row, column;
            column = dataGridView3.ColumnCount;
            row = dataGridView3.RowCount;
            int i, j;
            
            Stream myStream;
            myStream = saveFileDialog.OpenFile();
            StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));

            //sw.WriteLine("Welcome to C# world, Chris.");
            sw.WriteLine(DateTime.Now.ToString());
            sw.WriteLine();
            sw.WriteLine("Detailed Information for Adapter List:");
            for (i = 0; i < dataGridView6.RowCount; i++)
            {
                m_adptrname = dataGridView6[1, i].Value.ToString();
                sw.WriteLine("\t" + m_adptrname);
            }
            sw.WriteLine();
            sw.WriteLine();
            sw.WriteLine();
            sw.WriteLine("--------------------------------------------------------");
            sw.WriteLine();
            sw.WriteLine();
            sw.WriteLine();
            sw.WriteLine("Total Pin Numbers: " + m_totalp);
            sw.WriteLine();
            sw.WriteLine("Package Information: " + m_pckname);
            sw.WriteLine();
            sw.WriteLine();
            sw.WriteLine();
            sw.WriteLine("--------------------------------------------------------");
            sw.WriteLine();
            sw.WriteLine();
            sw.WriteLine();

            string contents = "";

            try
            {
                // move data into excel
                for (i = 0; i < row; i++)
                {
                    contents = "\t\t";
                    for (j = 0; j < column; j++)
                    {
                        if (j > 0)
                        {
                            contents += "\t\t";
                        }

                        if (dataGridView3[j, i].Value != null)
                        {
                            contents += dataGridView3[j, i].Value.ToString();
                        }
                        else
                        {
                            contents += "";
                        }
                    }

                    // write data
                    sw.WriteLine(contents);
                    sw.WriteLine();
                }

                if (dataGridView4.RowCount > 0)
                {
                    sw.WriteLine();
                    sw.WriteLine();
                    sw.WriteLine();
                    sw.WriteLine("--------------------------------------------------------");
                    sw.WriteLine();
                    sw.WriteLine();
                    sw.WriteLine();
                    // move note list into excel
                    for (i = 0; i < dataGridView4.RowCount; i++)
                    {
                        sw.WriteLine("\t " + dataGridView4[1, i].Value.ToString());
                    }
                }

                if (dataGridView5.RowCount > 0)
                {
                    sw.WriteLine();
                    sw.WriteLine();
                    sw.WriteLine();
                    sw.WriteLine("--------------------------------------------------------");
                    sw.WriteLine();
                    sw.WriteLine();
                    sw.WriteLine();
                    // move image list into excel
                    //Bitmap bitmap = null;
                    //byte[] imageDataDetails;
                    //int length;
                    for (i = 0; i < dataGridView5.RowCount; i++)
                    {
                        //FileStream fs = new FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                        //byte[] buffByte = new byte[fs.Length];
                        //fs.Read(buffByte, 0, (int)fs.Length); 
                        //imageDataDetails = (byte[])dataGridView5[1, i].Value;
                        //length = imageDataDetails.GetLength(0);
                        //using (MemoryStream stream = new MemoryStream(length + 14))
                        //{
                        //    byte[] buffer = new byte[13];
                        //    buffer[0] = 0x42;
                        //    buffer[1] = 0x4d;

                        //    stream.Write(buffer, 0, 2);

                        //    byte[] bytes = BitConverter.GetBytes(length);
                        //    stream.Write(bytes, 0, 4);
                        //    buffer[0] = 0;
                        //    buffer[1] = 0;
                        //    buffer[2] = 0;
                        //    buffer[3] = 0;
                        //    stream.Write(buffer, 0, 4);
                        //    int num2 = 0x36;
                        //    bytes = BitConverter.GetBytes(num2);
                        //    stream.Write(bytes, 0, 4);
                        //    stream.GetBuffer();
                        //    stream.Write(imageDataDetails, 0, length);
                        //    bitmap = new Bitmap(stream);
                        //    bitmap.RotateFlip(RotateFlipType.Rotate180FlipX);
                        //    stream.Close();                        
                        //}
                    }
                }
                sw.Close();
                myStream.Close();
                // MessageBox.Show("Please check " + saveFileDialog.FileName + "!", "Informer");
            }
            catch //(Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            finally
            {
                sw.Close();
                myStream.Close();
                MessageBox.Show("Please check " + saveFileDialog.FileName + "!", "Informer");
            }

            return;
        }

        // padsTemp button
        private void button9_Click(object sender, EventArgs e)
        {
            padsTempToolStripMenuItem_Click(sender, e);
        }

        // rules of set color for labels in dataGridView3
        private void SetColorRules(string str, int myrr, int mycc, bool label_devpin)
        {
            // str: labels or devpins
            // myrr, mycc: row and column in dataGridView3
            // label_devpin: true - label, false - devpin
            if (null == str ||
                false == label_devpin)
            {
                return;
            }

            char[] mych = str.ToCharArray();
            int length = str.Length;
            if (2 < length &&
                "NOP" == str.Substring(0, 3))
            {
                dataGridView3[mycc, myrr].Style.BackColor = System.Drawing.Color.Gray;
            }
            else if (2 < length &&
                     "VCC" == str.Substring(0, 3))
            {
                dataGridView3[mycc, myrr].Style.BackColor = System.Drawing.Color.Red;
            }
            else if (2 < length &&
                     "GND" == str.Substring(0, 3))
            {
                dataGridView3[mycc, myrr].Style.BackColor = System.Drawing.Color.Green;
            }
            else if (5 < length &&
                     "TP_PIN" == str.Substring(0, 6))
            {
                dataGridView3[mycc, myrr].Style.BackColor = System.Drawing.Color.Blue;
            }
            else if (0 < length &&
                     ('*' == mych[0] || '#' == mych[0]))
            {
                dataGridView3[mycc, myrr].Style.BackColor = System.Drawing.Color.Brown;
            }
            else if (1 < length &&
                     'D' == mych[0] &&
                     ('0' <= mych[1] && '9' >= mych[1]))
            {
                dataGridView3[mycc, myrr].Style.BackColor = System.Drawing.Color.Yellow;
            }
            else if (1 < length &&
                     'A' == mych[0] &&
                     ('0' <= mych[1] && '9' >= mych[1]))
            {
                dataGridView3[mycc, myrr].Style.BackColor = System.Drawing.Color.YellowGreen;
                //dataGridView3[mycc, myrr].Style.BackColor = System.Drawing.Color.Violet;
            }
            else if (1 < length &&
                     'G' == mych[0] &&
                     ('1' <= mych[1] && '4' >= mych[1]))
            {
                dataGridView3[mycc, myrr].Style.BackColor = System.Drawing.Color.Purple;
            }
            else if (1 < length && 
                     'E' == mych[1])
            {
                dataGridView3[mycc, myrr].Style.BackColor = System.Drawing.Color.Orange;
            }
            else
            {
                dataGridView3[mycc, myrr].Style.BackColor = System.Drawing.Color.White;
            }
        }

        // set PinMapId
        private void textBox4_TextChanged(object sender, EventArgs e)
        {
            m_pinmapid = int.Parse(textBox4.Text);
        }

        // set PackageInfo
        private void textBox5_TextChanged(object sender, EventArgs e)
        {
            //m_pckinfo = textBox5.Text;
        }

        // set BodySize
        private void textBox6_TextChanged(object sender, EventArgs e)
        {
            //m_bodysize = double.Parse(textBox6.Text);
        }

        // set Width
        private void textBox7_TextChanged(object sender, EventArgs e)
        {
            //m_width = double.Parse(textBox7.Text);
        }

        // set Pitch
        private void textBox8_TextChanged(object sender, EventArgs e)
        {
            //m_pitch = double.Parse(textBox8.Text);
        }

        // set BallDiameter
        private void textBox9_TextChanged(object sender, EventArgs e)
        {
            //m_balldiameter = double.Parse(textBox9.Text);
        }

        // set BallHeight
        private void textBox10_TextChanged(object sender, EventArgs e)
        {
            //m_ballheight = double.Parse(textBox10.Text);
        }

        // set PkgHeight
        private void textBox11_TextChanged(object sender, EventArgs e)
        {
            //m_pkgheight = double.Parse(textBox11.Text);
        }

        // set SocketNum
        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            //m_socketnum = int.Parse(comboBox2.Text);
        }

        // set PinOneOri
        private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
        {
            //m_pinoneori = comboBox3.Text;
        }

        // Add a new notes
        private void button10_Click(object sender, EventArgs e)
        {
            if (m_login == false)
            {
                MessageBox.Show("Please log in first!", "Warning");
                return;
            }
            if (m_OperationMode == 1)
            {
                // if in Search Mode, return;
                MessageBox.Show("You can only modify note list under Define Mode.", "Warning");
                return;
            }
            // call the AddNewNotes dialog
            AddNewNotesForm ann = new AddNewNotesForm();
            if (ann.ShowDialog() != DialogResult.OK)
                return;

            int myrr;            
            myrr = dataGridView4.RowCount;
            
            dataGridView4.Rows.Add();
            dataGridView4[0, myrr].Value = myrr + 1;
            dataGridView4[1, myrr].Value = ann.m_notes;
            dataGridView4[0, myrr].Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridView4.CurrentCell = dataGridView4[1, myrr];            
        }

        // finish a new notes edit.
        private void dataGridView4_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            //textBox12.Text = dataGridView4.CurrentCell.Value.ToString();
        }

        // show current notes
        private void dataGridView4_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            ////MessageBox.Show("test");
            //if ("" != dataGridView4[1, dataGridView4.CurrentCell.RowIndex].Value.ToString())
            //    textBox12.Text = dataGridView4[1, dataGridView4.CurrentCell.RowIndex].Value.ToString();
        }

        // delete Notes
        private void button12_Click(object sender, EventArgs e)
        {
            if (m_login == false)
            {
                MessageBox.Show("Please log in first!", "Warning");
                return;
            }
            if (m_OperationMode == 1)
            {
                // if in Search Mode, return;
                MessageBox.Show("You can only modify note list under Define Mode.", "Warning");
                return;
            }
            if (dataGridView4.RowCount == 0)
                return;
            for (int i = dataGridView4.CurrentCell.RowIndex; i < dataGridView4.RowCount - 1; i++)
            {
                dataGridView4[0, i].Value = i + 1;
                dataGridView4[1, i].Value = dataGridView4[1, i + 1].Value;
            }
            dataGridView4.RowCount--;
        }

        // add image link
        private void button13_Click(object sender, EventArgs e)
        {
            if (m_login == false)
            {
                MessageBox.Show("Please log in first!", "Warning");
                return;
            }
            if (m_OperationMode == 1)
            {
                // if in Search Mode, return;
                MessageBox.Show("You can only modify image list under Define Mode.", "Warning");
                return;
            }
            // open image dialog
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Image files (*.*) | *.*";
            openFileDialog.FilterIndex = 0;
            openFileDialog.RestoreDirectory = true;
            // openFileDialog.CreatePrompt = true;
            openFileDialog.Title = "Open Image files";
            openFileDialog.ShowDialog();

            if (openFileDialog.FileName.IndexOf(":") < 0)
            {   // if click cancel
                return;
            }
            int myrr;
            myrr = dataGridView5.RowCount;

            dataGridView5.Rows.Add();
            dataGridView5.Rows[myrr].Height = 200;
            dataGridView5[0, myrr].Value = myrr + 1;
            dataGridView5[1, myrr].Value = Image.FromFile(openFileDialog.FileName);
            dataGridView5[2, myrr].Value = openFileDialog.FileName;
            dataGridView5[0, myrr].Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridView5.CurrentCell = dataGridView5[1, myrr];

            //从数据库读图片到picturebox

            //SqlConnection conn=new SqlConnection(@"data source=chenyuming2004VSdotNET;uid=sa;pwd=cym;database=lhf");

            //conn.Open();

            //SqlCommand cmd=new SqlCommand("select 照片 from fuser where password='1b'",conn);

            //SqlDataReader reader=cmd.ExecuteReader();

            //reader.Read();

            //MemoryStream buf=new MemoryStream((byte[])reader[0]);

            //Image image=Image.FromStream(buf,true);

            //pictureBox1.Image=image;


        }

        // delete image link
        private void button15_Click(object sender, EventArgs e)
        {
            if (m_login == false)
            {
                MessageBox.Show("Please log in first!", "Warning");
                return;
            }
            if (m_OperationMode == 1)
            {
                // if in Search Mode, return;
                MessageBox.Show("You can only modify image list under Define Mode.", "Warning");
                return;
            }
            if (0 == dataGridView5.RowCount)
                return;
            for (int i = dataGridView5.CurrentCell.RowIndex; i < dataGridView5.RowCount - 1; i++)
            {
                dataGridView5[0, i].Value = i + 1;
                dataGridView5[1, i].Value = dataGridView5[1, i + 1].Value;
            }
            dataGridView5.RowCount--;
            //pictureBox1.Image = null;
            if (dataGridView5.RowCount > 0)
                dataGridView5.CurrentCell = dataGridView5[1, dataGridView5.RowCount - 1];            
        }

        // show the selected image
        private void button14_Click(object sender, EventArgs e)
        {
            //string path = dataGridView5[1, dataGridView5.CurrentCell.RowIndex].Value.ToString();
            //pictureBox1.Image = Image.FromFile(path);
        }

        // Print Preview
        private void printPreToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (m_login == false)
            {
                MessageBox.Show("Please log in first!", "Warning");
                return;
            }
            if (dataGridView3.RowCount < 1 ||
                dataGridView3.ColumnCount < 1)
                return;

            Image temp = Image.FromFile(@"demo.jpg");
            GetResultIntoImage(ref temp, false);//, dataGridView3);
            PrintPrevForm ppf = new PrintPrevForm();
            ppf.pictureBox1.Image = temp;
            //ppf.pictureBox1.SizeMode = PictureBoxSizeMode.Normal;
            ppf.button3.Enabled = false;
            ppf.button4.Enabled = false;
            ppf.button5.Enabled = false;
            ppf.button3.Visible = false;
            ppf.button4.Visible = false;
            ppf.button5.Visible = false;
            ppf.Show();
            //temp.Save("test.jpg");
        }

        // Print dataGridView3 pin assignment array
        private void printToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (m_login == false)
            {
                MessageBox.Show("Please log in first!", "Warning");
                return;
            }
            if (dataGridView3.RowCount < 1 ||
                dataGridView3.ColumnCount < 1)
                return;

            PrintDocument pd = new PrintDocument();

            Margins margin = new Margins(20, 20, 20, 20);
            pd.DefaultPageSettings.Margins = margin;
            
            pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);

            //PrintPreviewDialog ppdi = new PrintPreviewDialog();
            //ppdi.Document = pd;
            //ppdi.ShowDialog();
            //return;

            PrintDialog printd1 = new PrintDialog();
            printd1.ShowNetwork = false;
            printd1.PrintToFile = false;
            printd1.Document = pd;
            if (printd1.ShowDialog() != DialogResult.Cancel)
            {
                try
                {
                    pd.Print();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Print Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    pd.PrintController.OnEndPrint(pd, new PrintEventArgs());
                }
            }
        }

        // pd_PrintPage 
        private void pd_PrintPage(object sender, PrintPageEventArgs e)
        {
            Image temp = Image.FromFile(@"demo.jpg");
            GetResultIntoImage(ref temp, false);//, dataGridView3);
            //pictureBox1.Image = temp;
            int x = e.MarginBounds.X;   
            int y = e.MarginBounds.Y;   
            int width = temp.Width;   
            int height = temp.Height;   
            Rectangle destRect = new Rectangle(x, y, width, height);
            e.HasMorePages = false;
            //float linesPerPage = 0;
            //linesPerPage = e.MarginBounds.Height / p
            e.Graphics.DrawImage(temp, destRect, 0, 0, temp.Width,    
                temp.Height, System.Drawing.GraphicsUnit.Pixel);  
        }

        private void GetResultIntoImage( ref Image temp, bool mcolor)//, DataGridView dgv)            
        {   //C#打印原理之读取图片模板   
            Graphics g = Graphics.FromImage(temp);   
            Font f = new Font("微软雅黑", 12);  
            Brush b = new SolidBrush(Color.Black);   //C#打印原理之填充数据到图片模板（位置要在制作图片模板的时候度量好）   
            Pen p = new Pen(b);
            g.DrawImage(temp, 0, 0, temp.Width, temp.Height);
            int xx, yy, ww, hh;
            
            // draw datagridview to image
            DataGridView dgv = new DataGridView();
            // 1. dataGridView6: AdapterList
            dgv = dataGridView6;
            xx = 100;
            yy = 50;
            if (dgv.RowCount > 0)
            {
                for (int i = 0; i < dgv.RowCount; i++)
                {
                    yy += 50;
                    g.DrawString(dgv[1, i].Value.ToString() + "\tSocket Id: " + dgv[2, i].Value.ToString(), f, b, xx, yy);
                }
            }
            
            // 2. dataGridView3: PinAssignmentArray
            dgv = dataGridView3;
            int row = dgv.RowCount;
            int column = dgv.ColumnCount;
            int tt;
            int tempx, tempy;
            tempx = xx;
            tempy = yy + 50;
            // original point (x, y) = (50, 100)
            for (int i = 0; i < row; i++)
            {
                for (int j = 0; j < column; j++)
                { 
                    // drawrectangle
                    // prepare the rect
                    xx = tempx;
                    for (tt = 0; tt < j; tt++)
                    {
                        xx += dgv[tt, i].Size.Width;
                    }
                    yy = tempy;
                    for (tt = 0; tt < i; tt++)
                    {
                        yy += dgv[j, tt].Size.Height;
                    }
                    ww = dgv[j, i].Size.Width;
                    hh = dgv[j, i].Size.Height;
                    Rectangle rect = new Rectangle(xx, yy, ww, hh);
                    if (mcolor)
                    {
                        b = new SolidBrush(dgv[j, i].Style.BackColor);
                        g.FillRectangle(b, rect);
                    }
                    g.DrawRectangle(p, rect);
                    
                    // draw the content
                    if (null != dgv[j, i].Value)
                    {
                        //g.DrawRectangle(p, rect);
                        f = dgv.Font;
                        xx += dgv[j, i].Size.Width / 8;
                        yy += dgv[j, i].Size.Height / 4;
                        b = new SolidBrush(Color.Black);
                        g.DrawString(dgv[j, i].Value.ToString(), f, b, xx, yy);
                    }
                }
            }

             //3. dataGridView4: NoteList
            dgv = dataGridView4;
            if (dgv.RowCount > 0)
            {
                xx = tempx;
                for (int i = 0; i < dgv.RowCount; i++)
                {
                    if (i == 0)
                        yy += 100;
                    else
                        yy += 50;
                    //f = dgv.Font;
                    f = new Font("微软雅黑", 10);
                    g.DrawString(dgv[1, i].Value.ToString(), f, b, xx, yy);
                }
            }

            // 4. dataGridView5: ImageList
            dgv = dataGridView5;
            if (dgv.RowCount > 0)
            {
                xx = tempx;
                for (int i = 0; i < dgv.RowCount; i++)
                {
                    if (i == 0)
                        yy += 100;
                    else
                        yy += 200;
                    g.DrawImage((Image)dgv[1, i].Value, xx, yy);
                    //g.DrawString(dgv[1, i].Value.ToString(), f, b, 50, 50);
                }
            }
            g.Dispose();  
 
            // Bitmap bmp = new Bitmap()
        }

        // commit any changes
        private void button7_Click(object sender, EventArgs e)
        {
            if (m_login == false)
            {
                MessageBox.Show("Please log in first!", "Warning");
                return;
            }
            if (m_OperationMode == 1)
            {
                // if in Search Mode, return;
                MessageBox.Show("You can only modify pinmap under Define Mode.", "Warning");
                return;
            }
            statusStrip.Text = "Saving to database ... ";

            int tab_index = tabControl1.SelectedIndex;
            //MessageBox.Show("tab_index is " + tab_index.ToString());

            int i = 0;

            switch (tab_index)
            {
                case 0:
                    if (dataGridView3.RowCount < 1)
                    {
                        break;
                    }
                    // under PinMap Tab
                    // update PinMapListTable
                    PinMapListElement pmle = new PinMapListElement();
                    pmle.PinMapId = m_pinmapid;
                    pmle.PackageName = m_pckname;
                    pmle.RowNum = m_rownum;
                    pmle.ColumnNum = m_columnum;
                    pmle.TotalPins = m_totalp;
                    // query into the database, if exist this pinmapid, update records, if not exist insert records.
                    AccessDataBase adb1 = new AccessDataBase();
                    if (adb1.QueryExistPinMapListTable(m_pinmapid))
                    {
                        // exist, update records
                        adb1.UpdateRecPinMapListTable(pmle);
                    }
                    else
                    {
                        // not exist, insert records
                        m_pinmapid = adb1.InsertRecPinMapListTable(pmle);
                        pmle.PinMapId = m_pinmapid;
                        textBox4.Text = m_pinmapid.ToString();
                    }

                    // update PinOutListTable
                    for (i = 0; i < m_listsize; i++)
                    {
                        // if exist PinMapId & Position, update, if not exist insert
                        if ("" != m_labelist[i])
                        {
                            PinOutListElement pole = new PinOutListElement();
                            pole.PinMapId = m_pinmapid;
                            pole.Position = m_posilist[i];
                            pole.Label = m_labelist[i];
                            pole.DevicePin = m_devpinlist[i];

                            if (adb1.QueryExistPinOutListTable(m_pinmapid, pole.Position))
                            {
                                // update
                                adb1.UpdateRecPinoutListTable(pole);
                            }
                            else
                            {
                                // insert
                                adb1.InsertRecPinOutListTable(pole);
                            }
                        }
                    }
                    MessageBox.Show("PinMapListTable and PinOutListTable Saved finished!", "Note");
                    break;
                case 1:
                    if (dataGridView4.RowCount < 1 &&
                        dataGridView5.RowCount < 1)
                    {
                        break;
                    }
                    // under NoteImageList Tab
                    AccessDataBase adb2 = new AccessDataBase();
                    // commit NoteListTable
                    if (dataGridView4.RowCount > 0)
                    {
                        // 1. Query PinMapId existed in PinMapListTable                        
                        if (!adb2.QueryExistPinMapListTable(m_pinmapid))
                        {
                            break;
                        }
                        // 2. Query PinMapId existed in NoteListTable
                        if (adb2.QueryExistNoteListTable(m_pinmapid))
                        {
                            // 3. Delete all records of PinMapId
                            adb2.DeleteRecNoteListTable(m_pinmapid);
                        }
                        // 4. Insert new records of PinMapId
                        for (i = 0; i < dataGridView4.RowCount; i++)
                        {
                            NoteListElement nle = new NoteListElement();
                            nle.PinMapId = m_pinmapid;
                            nle.NoteId = int.Parse(dataGridView4[0, i].Value.ToString());
                            nle.Notes = dataGridView4[1, i].Value.ToString();
                            adb2.InsertRecNoteListTable(nle);
                        }
                    }
                    if (dataGridView5.RowCount > 0)
                    {
                        // 1. Query PinMapId existed in PinMapListTable                        
                        if (!adb2.QueryExistPinMapListTable(m_pinmapid))
                        {
                            break;
                        }
                        // 2. Query PinMapId exister in ImageListTable
                        if (adb2.QueryExistImageListTable(m_pinmapid))
                        {
                            // 3. Delete all records of PinMapId
                            adb2.DeleteRecImageListTable(m_pinmapid);
                        }
                        // 4. Insert new records of PinMapId
                        string filename;
                        for (i = 0; i < dataGridView5.RowCount; i++)
                        {
                            ImageListElement ile = new ImageListElement();
                            ile.PinMapId = m_pinmapid;
                            ile.ImageId = int.Parse(dataGridView5[0, i].Value.ToString());
                            filename = dataGridView5[2, i].Value.ToString();
                            FileStream fs = new FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                            byte[] buffByte = new byte[fs.Length];
                            fs.Read(buffByte, 0, (int)fs.Length);                            
                            //ile.Images = Image.FromStream(fs);
                            fs.Close();
                            ile.ImagesByte = buffByte;
                            adb2.InsertRecImageListTable(ile);
                        }
                    }
                    
                    MessageBox.Show("NoteListTable and ImageListTable Saved finished!", "Note");
                    break;
                case 2:
                    // under AdapterList Tab
                    if (dataGridView6.RowCount < 1)
                    {
                        break;
                    }
                    AccessDataBase adb3 = new AccessDataBase();
                    // 1. Query PinMapId existed in PinMapListTable
                    if (!adb3.QueryExistPinMapListTable(m_pinmapid))
                    {
                        break;
                    }
                    for (int n = 0; n < dataGridView6.RowCount; n++)
                    {
                        AdapterListTableElement alte = new AdapterListTableElement();
                        HWParamTableElement hwpte = new HWParamTableElement();
                        AdapterOptionIdElement aoie = new AdapterOptionIdElement();
                        m_adptrid = int.Parse(dataGridView6[0, n].Value.ToString());
                        m_socketid = dataGridView6[2, n].Value.ToString();
                        
                        alte.AdapterId = m_adptrid;
                        alte.PinMapId = m_pinmapid;
                        alte.SocketId = m_socketid;
                        alte.AdapterName = dataGridView6[1, n].Value.ToString();
                        alte.PackageInfo = dataGridView7[n + 1, 1].Value.ToString();
                        //if (dataGridView6[2, n].EditedFormattedValue.ToString() == "True")
                        //{
                        //    alte.HIC = 1;
                        //}
                        //else
                        //{
                        //    alte.HIC = 0;
                        //}

                        hwpte.SocketId = m_socketid;
                        //hwpte.PackageInfo = dataGridView7[n + 1, 1].Value.ToString();
                        alte.SocketNum = int.Parse(dataGridView7[n + 1, 2].Value.ToString());
                        alte.PinOneOri = dataGridView7[n + 1, 3].Value.ToString();
                        hwpte.BodySize = double.Parse(dataGridView7[n + 1, 4].Value.ToString());
                        hwpte.Width = double.Parse(dataGridView7[n + 1, 5].Value.ToString());
                        hwpte.Pitch = double.Parse(dataGridView7[n + 1, 6].Value.ToString());
                        hwpte.BallDiameter = double.Parse(dataGridView7[n + 1, 7].Value.ToString());
                        hwpte.BallHeight = double.Parse(dataGridView7[n + 1, 8].Value.ToString());
                        hwpte.PkgHeight = double.Parse(dataGridView7[n + 1, 9].Value.ToString());

                        // 2. Query AdapterId exister in AdapterListTable
                        if (adb3.QueryExistAdapterListTable(m_adptrid))
                        {
                            // update three tables
                            adb3.UpdateRecAdapterListTable(alte);
                            if (!adb3.QueryRecHWParamTable(hwpte.SocketId))
                            {
                                adb3.InsertRecHWParamTable(hwpte);
                            }
                            else
                            {
                                adb3.UpdateRecHWParamTable(hwpte);
                            }
                            for (int b = 1; b < dataGridView8.RowCount; b++)
                            {
                                aoie.AdapterId = m_adptrid;
                                aoie.Position = dataGridView8[0, b].Value.ToString();
                                aoie.OptionId = int.Parse(dataGridView8[n + 1, b].Value.ToString());
                                adb3.UpdateRecAdapterOptionIDTable(aoie);
                            }
                        }
                        else
                        {
                            // insert three tables
                            adb3.InsertRecAdapterListTable(alte);
                            if (!adb3.QueryRecHWParamTable(hwpte.SocketId))
                            {
                                adb3.InsertRecHWParamTable(hwpte);
                            }
                            else
                            {
                                adb3.UpdateRecHWParamTable(hwpte);
                            }
                            for (int v = 1; v < dataGridView8.RowCount; v++)
                            {
                                aoie.AdapterId = m_adptrid;
                                aoie.Position = dataGridView8[0, v].Value.ToString();
                                aoie.OptionId = int.Parse(dataGridView8[n + 1, v].Value.ToString());
                                adb3.InsertRecAdapterOptionIdTable(aoie);
                            }
                        }
                    }
                    MessageBox.Show("AdapterList, HWParamTable and AdapterOptionIdTable Saved finished!", "Note");
                    break;
                case 3:
                    // under AdapterLookuUp Tab
                    break;
            }
            statusStrip.Text = "Ready";
        }

        // exit the software using button16
        private void button16_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Do you really want to exit this tool?", "Exit Confirm", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                this.Close();
            }
        }

        private void textBox4_TextChanged_1(object sender, EventArgs e)
        {
            //if (m_lock)
            //{
            //    MessageBox.Show("The record is locked.", "Note");
            //    return;
            //}
            m_pinmapid = int.Parse(textBox4.Text);
        }

        private void button11_Click(object sender, EventArgs e)
        {
            //// preview all the notes using PrintPrevForm
            //if (dataGridView4.RowCount < 1 ||
            //    dataGridView4.ColumnCount < 1)
            //    return;

            //Image temp = Image.FromFile(@"demo.jpg");
            //GetResultIntoImage(ref temp, dataGridView4);
            //PrintPrevForm ppf = new PrintPrevForm();
            //ppf.pictureBox1.Image = temp;
            //ppf.Show();
        }

        // add Adapter to the AdapterList
        private void button1_Click(object sender, EventArgs e)
        {
            if (m_login == false)
            {
                MessageBox.Show("Please log in first!", "Warning");
                return;
            }
            if (m_OperationMode == 1)
            {
                // if in Search Mode, return;
                MessageBox.Show("You can only add Adapter to List under Define Mode.", "Warning");
                return;
            }

            int myrr, mycc;
            // add row to the datagridview6
            if (m_listsize == 0)
            {
                return;
            }
            myrr = dataGridView6.RowCount;
            dataGridView6.Rows.Add("", "PA-" + m_pcktype + "000", "0");

            // add column to the datagridview7
            if (dataGridView7.ColumnCount == 1)
            {
                //DataGridViewTextBoxColumn dgvtbc = new DataGridViewTextBoxColumn();
                //dgvtbc.HeaderText = "";
                //dataGridView7.Columns.Add(dgvtbc);
                // add the row header first
                dataGridView7.Rows.Add("<HWParams>");
                ////dataGridView7.Rows.Add("HWParamId");
                dataGridView7.Rows.Add("PackageInfo");
                dataGridView7.Rows.Add("SocketNum");
                dataGridView7.Rows.Add("PinOneOri");
                dataGridView7.Rows.Add("BodySize");
                dataGridView7.Rows.Add("Width");
                dataGridView7.Rows.Add("Pitch");
                dataGridView7.Rows.Add("BallDiameter");
                dataGridView7.Rows.Add("BallHeight");
                dataGridView7.Rows.Add("PkgHeight");
                //dataGridView7[0, 0].Style.BackColor = System.Drawing.Color.Blue;
                dataGridView7.Columns[0].ReadOnly = true;
                dataGridView7.Rows[0].ReadOnly = true;
                for (int i = 0; i < 10; i++)
                {
                    dataGridView7.Rows[i].Height = 42;
                    dataGridView7[0, i].Style.BackColor = System.Drawing.Color.Pink;
                }
            }
            mycc = dataGridView7.ColumnCount;
            DataGridViewTextBoxColumn dgvtbc1 = new DataGridViewTextBoxColumn();
            dgvtbc1.HeaderText = "AdapterId";
            dgvtbc1.Width = 60;
            dataGridView7.Columns.Add(dgvtbc1);
            dataGridView7[mycc, 1].Value = m_pckname + "-" + m_totalp.ToString();
            dataGridView7[mycc, 2].Value = 4;
            dataGridView7[mycc, 3].Value = "UL";
            for (int j = 4; j < 10; j++)
            {
                dataGridView7[mycc, j].Value = 0.0;
            }
            dataGridView7[mycc, 0].Style.BackColor = System.Drawing.Color.Cyan;
            dataGridView7.Columns[mycc].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            
            // add column to the datagridview8
            if (dataGridView8.ColumnCount == 1)
            {
                dataGridView8.Rows.Add("<Loc>");
                for (int k = 0; k < m_listsize; k++)
                {
                    dataGridView8.Rows.Add(m_posilist[k]);
                }
                dataGridView8.Columns[0].ReadOnly = true;
                dataGridView8.Rows[0].ReadOnly = true;
                //dataGridView8[0, 0].Style.BackColor = System.Drawing.Color.Blue;
                dataGridView8.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                for (int l = 0; l <= m_listsize; l++)
                {
                    dataGridView8.Rows[l].Height = 30;
                    dataGridView8[0, l].Style.BackColor = System.Drawing.Color.Pink;
                }
            }
            mycc = dataGridView8.ColumnCount;
            DataGridViewTextBoxColumn dgvtbc2 = new DataGridViewTextBoxColumn();
            dgvtbc2.HeaderText = "AdptrId";
            dgvtbc2.Width = 60;
            dataGridView8.Columns.Add(dgvtbc2);
            dataGridView8.Columns[mycc].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            for (int m = 0; m < m_listsize; m++)
            {
                dataGridView8[mycc, m + 1].Value = 1;
            }
            dataGridView8[mycc, 0].Style.BackColor = System.Drawing.Color.Cyan;
        }

        // delete adapter list
        private void button2_Click(object sender, EventArgs e)
        {
            if (m_login == false)
            {
                MessageBox.Show("Please log in first!", "Warning");
                return;
            }
            if (m_OperationMode == 1)
            {
                // if in Search Mode, return;
                MessageBox.Show("You can only add Adapter to List under Define Mode.", "Warning");
                return;
            }
            if (dataGridView6.RowCount == 0)
            {
                return;
            }
            else if (dataGridView6.RowCount == 1)
            {
                int rowindx = dataGridView6.CurrentCell.RowIndex;
                dataGridView6.Rows.RemoveAt(rowindx);
                dataGridView7.Columns.RemoveAt(rowindx + 1);
                dataGridView8.Columns.RemoveAt(rowindx + 1);
                dataGridView7.RowCount = 0;
                dataGridView8.RowCount = 0;
            }
            else
            {
                int rowindx1 = dataGridView6.CurrentCell.RowIndex;
                dataGridView6.Rows.RemoveAt(rowindx1);
                dataGridView7.Columns.RemoveAt(rowindx1 + 1);
                dataGridView8.Columns.RemoveAt(rowindx1 + 1);
            }
            
        }

        // edit adapter list
        private void dataGridView6_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            // update dataGridView6 into dataGridView7 and dataGridView8
            int myr, myc;
            myc = dataGridView6.CurrentCell.ColumnIndex;
            myr = dataGridView6.CurrentCell.RowIndex;
            m_pckname = comboBox1.Text;
            switch (m_pckname)
            { 
                case "DIP":
                    m_pcktype = "D";
                    break;
                case "BGA":
                    m_pcktype = "G";
                    break;
                case "LGA":
                case "QFN":
                    m_pcktype = "L";
                    break;
                case "SOIC":
                    m_pcktype = "S";
                    break;
                case "TSOP":
                    m_pcktype = "T";
                    break;
                case "PLCC":
                    m_pcktype = "P";
                    break;
                case "QFP":
                    m_pcktype = "Q";
                    break;
            }

            switch (myc)
            { 
                case 0:
                    // AdapterId changed
                    m_adptrid = int.Parse(dataGridView6.CurrentCell.Value.ToString());
                    if (m_adptrid < 10)
                    {
                        m_adptrname = "PA-" + m_pcktype + "00" + m_adptrid.ToString();
                    }
                    else if (m_adptrid < 100)
                    {
                        m_adptrname = "PA-" + m_pcktype + "0" + m_adptrid.ToString();
                    }
                    else
                    {
                        m_adptrname = "PA-" + m_pcktype + m_adptrid.ToString();
                    }
                    if (dataGridView6[2, myr].EditedFormattedValue.ToString() == "True")
                    {
                        m_adptrname += "HIC";
                    }
                    dataGridView6[1, myr].Value = m_adptrname;
                    dataGridView7[myr + 1, 0].Value = dataGridView6[0, myr].Value;
                    dataGridView8[myr + 1, 0].Value = dataGridView6[0, myr].Value;
                    break;
                case 1:
                    // AdapterName changed
                    break;
                case 2:
                    // HIC changed
                    //if (dataGridView6[0, myr].Value == null ||
                    //    dataGridView6[0, myr].Value == "")
                    //{
                    //    m_adptrid = 0;
                    //}
                    //else
                    //{
                    //    m_adptrid = int.Parse(dataGridView6[0, myr].Value.ToString());
                    //}
                    //if (m_adptrid < 10)
                    //{
                    //    m_adptrname = "PA-" + m_pcktype + "00" + m_adptrid.ToString();
                    //}
                    //else if (m_adptrid < 100)
                    //{
                    //    m_adptrname = "PA-" + m_pcktype + "0" + m_adptrid.ToString();
                    //}
                    //else
                    //{
                    //    m_adptrname = "PA-" + m_pcktype + m_adptrid.ToString();
                    //}
                    //if (dataGridView6.CurrentCell.EditedFormattedValue.ToString() == "True")
                    //{
                    //    m_adptrname += "HIC";
                    //}
                    //dataGridView6[1, myr].Value = m_adptrname;
                    break;
            }            
        }

        private void label27_Click(object sender, EventArgs e)
        {

        }

        private void label26_Click(object sender, EventArgs e)
        {

        }

        // zoom in and zom out
        private void button11_Click_1(object sender, EventArgs e)
        {
            if (m_login == false)
            {
                MessageBox.Show("Please log in first!", "Warning");
                return;
            }
            // Zoom dataGirdView3
            if (dataGridView3.RowCount < 1)
            {
                return;
            }
            m_viewover = !m_viewover;
            int h_view, w_view, h_dgv, w_dgv;
            h_view = dataGridView3.Height;
            w_view = dataGridView3.Width;
            h_dgv = 0;
            for (int i = 0; i < dataGridView3.RowCount; i++)
            {
                h_dgv += dataGridView3.Rows[i].Height;
            }
            w_dgv = 0;
            for (int j = 0; j < dataGridView3.ColumnCount; j++)
            {
                w_dgv += dataGridView3.Columns[j].Width;
            }
            double h_scl, w_scl;
            h_scl = (double)h_view / (double)h_dgv;
            w_scl = (double)w_view / (double)w_dgv;

            //MessageBox.Show(h_view.ToString() + " *** " +
            //                w_view.ToString() + " *** " +
            //                h_dgv.ToString() + " *** " +
            //                w_dgv.ToString());

            int a;
            if (m_viewover)
            {
                // zoom to view overall
                // calculate the scale
                if (h_scl > 1.0 && w_scl > 1.0)
                {
                    m_scales = (h_scl < w_scl) ? h_scl : w_scl;
                }
                else if (h_scl < 1.0 && w_scl < 1.0)
                {
                    m_scales = (h_scl < w_scl) ? h_scl : w_scl;
                }
                else if (h_scl < 1.0 && w_scl > 1.0)
                {
                    m_scales = h_scl;
                }
                else if (h_scl > 1.0 && w_scl < 1.0)
                {
                    m_scales = w_scl;
                }

                for (a = 0; a < dataGridView3.RowCount; a++)
                {
                    dataGridView3.Rows[a].Height = (int)(m_scales * (double)dataGridView3.Rows[a].Height);
                }
                for (a = 0; a < dataGridView3.ColumnCount; a++)
                {
                    dataGridView3.Columns[a].Width = (int)(m_scales * (double)dataGridView3.Columns[a].Width);
                }
            }
            else
            { 
                // show normal
                for (a = 0; a < dataGridView3.RowCount; a++)
                {
                    dataGridView3.Rows[a].Height = (int)((double)dataGridView3.Rows[a].Height / m_scales);
                }
                for (a = 0; a < dataGridView3.ColumnCount; a++)
                {
                    dataGridView3.Columns[a].Width = (int)((double)dataGridView3.Columns[a].Width / m_scales);
                }
            }
        }

        // search
        private void button3_Click(object sender, EventArgs e)
        {
            // clear search result
            dataGridView9.RowCount = 0;
            if (m_login == false)
            {
                MessageBox.Show("Please log in first!", "Warning");
                return;
            }
            if (m_OperationMode == 0)
            {
                // if in Define Mode, return;
                MessageBox.Show("You can search under Search Mode.", "Warning");
                return;
            }
            statusStrip.Text = "Searching ... ";
            AccessDataBase adb = new AccessDataBase();
            int adptrid;
            adptrid = int.Parse(textBox1.Text);
            if (0 != adptrid)
            { 
                // only query adptrid
                if (!adb.QueryExistAdapterListTable(adptrid))
                {
                    MessageBox.Show("Don't find records in the Database!", "Note");
                    statusStrip.Text = "Ready";
                    return;
                }
                // exist the adapter
                dataGridView9.RowCount = 0;
                AdapterListTableElement alte1 = new AdapterListTableElement();
                alte1 = adb.LoadAdapterListTable(adptrid);
                dataGridView9.Rows.Add(alte1.AdapterId.ToString(), alte1.AdapterName, alte1.SocketNum.ToString());
                statusStrip.Text = "Ready";
                return;
            }
            int n1, n2;
            int[] list1 = new int[6];
            int[] list2 = new int[3];
            double[] valist1 = new double[6];
            string[] valist2 = new string[3];
            n1 = CheckQ1HW(ref list1, ref valist1);
            n2 = CheckQ1PM(ref list2, ref valist2);

            int m1, m2, m = 0;
            int[] adapterlist = new int[2000];
            int[] pinmaplist = new int[1000];
            int[] alist1 = new int[2000];
            int[] alist2 = new int[2000];
            if (0 == n2)
            {
                // only consider the hw info
                m = adb.QueryAdapter4HWParamTable(ref adapterlist, list1, valist1, n1);
            }
            else if (0 == n1)
            {
                // only consider the pinmap info
                m2 = adb.QueryPinMap4PinMapListTable(ref pinmaplist, list2, valist2, n2);
                m = adb.QueryAdapter4AdapterListTable(ref adapterlist, pinmaplist, m2);
            }
            else
            {
                // need cross checking
                m1 = adb.QueryAdapter4HWParamTable(ref alist1, list1, valist1, n1);
                int temp = adb.QueryPinMap4PinMapListTable(ref pinmaplist, list2, valist2, n2);
                m2 = adb.QueryAdapter4AdapterListTable(ref alist2, pinmaplist, temp);
                m = CrossCheck2List(ref adapterlist, alist1, m1, alist2, m2);
            }

            // fill the adapter list
            dataGridView9.RowCount = 0;
            if (0 == m)
            {
                MessageBox.Show("Don't find records in the Database!", "Note");
                statusStrip.Text = "Ready";
                return;
            }
            for (int i = 0; i < m; i++)
            {
                AdapterListTableElement alte = new AdapterListTableElement();
                alte = adb.LoadAdapterListTable(adapterlist[i]);
                dataGridView9.Rows.Add(alte.AdapterId.ToString(), alte.AdapterName, alte.SocketNum.ToString());
            }
            statusStrip.Text = "Ready";
        } 

        // get hwp query list
        public int CheckQ1HW(ref int[] posilist, ref double[] valist)
        {
            int n = 0;

            if (comboBox8.Text != "Any")
            {
                posilist[n] = 1;
                valist[n] = double.Parse(comboBox8.Text);
                n++;
            }
            if (comboBox9.Text != "Any")
            {
                posilist[n] = 2;
                valist[n] = double.Parse(comboBox9.Text);
                n++;
            }
            if (comboBox10.Text != "Any")
            {
                posilist[n] = 3;
                valist[n] = double.Parse(comboBox10.Text);
                n++;
            }
            if (comboBox11.Text != "Any")
            {
                posilist[n] = 4;
                valist[n] = double.Parse(comboBox11.Text);
                n++;
            }
            if (comboBox12.Text != "Any")
            {
                posilist[n] = 5;
                valist[n] = double.Parse(comboBox12.Text);
                n++;
            }
            if (comboBox13.Text != "Any")
            {
                posilist[n] = 6;
                valist[n] = double.Parse(comboBox13.Text);
                n++;
            }

            return n;
        }

        // get pin query list
        public int CheckQ1PM(ref int[] posilist, ref string[] valist)
        {
            int n = 0;
            if (comboBox5.Text != "Any")
            {
                posilist[n] = 1;
                valist[n] = comboBox5.Text;
                n++;
            }
            if (comboBox6.Text != "Any")
            {
                posilist[n] = 2;
                valist[n] = comboBox6.Text;
                n++;
            }
            if (comboBox7.Text != "Any")
            {
                posilist[n] = 3;
                valist[n] = comboBox7.Text;
                n++;
            }

            return n;
        }

        // cross checking two lists
        public int CrossCheck2List(ref int[] list_dst, int[] list1, int num1, int[] list2, int num2)
        {
            int ret = 0;
            for (int i = 0; i < num1; i++)
            {
                for (int j = 0; j < num2; j++)
                {
                    if (list1[i] == list2[j])
                    {
                        list_dst[ret] = list1[i];
                        ret++;
                        j = num2;
                    }
                }
            }
            
            return ret;
        }

        // clear Q1
        private void button18_Click(object sender, EventArgs e)
        {
            if (m_login == false)
            {
                MessageBox.Show("Please log in first!", "Warning");
                return;
            }
            comboBox5.Text = "Any";
            comboBox6.Text = "Any";
            comboBox7.Text = "Any";
            comboBox8.Text = "Any";
            comboBox9.Text = "Any";
            comboBox10.Text = "Any";
            comboBox11.Text = "Any";
            comboBox12.Text = "Any";
            comboBox13.Text = "Any";
        }

        // clear Q2
        private void button17_Click(object sender, EventArgs e)
        {
            if (m_login == false)
            {
                MessageBox.Show("Please log in first!", "Warning");
                return;
            }
            dataGridView10.RowCount = 0;
        }

        // create array
        private void button19_Click(object sender, EventArgs e)
        {
            if (m_login == false)
            {
                MessageBox.Show("Please log in first!", "Warning");
                return;
            }
            if (comboBox5.Text == "Any" ||
                comboBox6.Text == "Any" ||
                comboBox7.Text == "Any")
            {
                return;
            }

            m_pckname = comboBox5.Text;
            m_rownum = int.Parse(comboBox6.Text);
            m_columnum = int.Parse(comboBox7.Text);

            switch (m_pckname)
            {
                case "BGA":
                case "LGA":
                    // create BGA_LGAAdapter
                    BGA_LGAAdapter blgaadptr = new BGA_LGAAdapter();
                    blgaadptr.PinMapId = m_pinmapid;
                    blgaadptr.RowNum = m_rownum;
                    blgaadptr.ColumnNum = m_columnum;

                    m_listsize = m_rownum * m_columnum;
                    m_posilist = blgaadptr.PositionList;
                    m_labelist = blgaadptr.LabelList;

                    break;
                case "DIP":
                case "SOIC":
                case "TSOP":
                    //create DIP_TSOP_SOICAdapter
                    DIP_TSOP_SOICAdapter dtsadptr = new DIP_TSOP_SOICAdapter();
                    dtsadptr.PinMapId = m_pinmapid;
                    dtsadptr.RowNum = m_rownum;
                    m_columnum = 2;
                    numericUpDown2.Value = m_columnum;

                    m_listsize = m_rownum * 2;
                    m_posilist = dtsadptr.PositionList;
                    m_labelist = dtsadptr.LabelList;

                    break;
                case "QFP":
                case "PLCC":
                    // create QFPAdatper
                    QFP_PLCCAdapter qpadptr = new QFP_PLCCAdapter();
                    qpadptr.PinMapId = m_pinmapid;
                    qpadptr.RowNum = m_rownum;
                    qpadptr.ColumnNum = m_columnum;

                    m_listsize = (m_rownum + m_columnum) * 2;
                    m_posilist = qpadptr.PositionList;
                    m_labelist = qpadptr.LabelList;

                    break;
                case "QFN":
                    // create QFNAdapter
                    QFNAdapter qnadptr = new QFNAdapter();
                    qnadptr.PinMapId = m_pinmapid;
                    qnadptr.RowNum = m_rownum;
                    qnadptr.ColumnNum = m_columnum;

                    m_listsize = (m_rownum + m_columnum) * 2 + 1;
                    m_posilist = qnadptr.PositionList;
                    m_labelist = qnadptr.LabelList;

                    break;
            }
            m_devpinlist = new string[m_listsize];
            for (int k = 0; k < m_listsize; k++)
            {
                m_devpinlist[k] = "";
            }

            m_totalp = 0;
            int i, j;
            
            // draw dataGridView10, pin assignmeng array
            dataGridView10.RowCount = 0;
            dataGridView10.ColumnCount = 0;
            switch (m_pckname)
            {
                case "DIP":
                case "SOIC":
                case "TSOP":
                    for (i = 0; i < m_columnum + 5; i++)
                    {
                        dataGridView10.Columns.Add("column" + i.ToString(), "");
                        dataGridView10.Columns[i].Width = 50;
                        dataGridView10.Columns[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                    }

                    for (i = 0; i < m_rownum; i++)
                    {
                        dataGridView10.Rows.Add();
                    }

                    for (i = 0; i < m_rownum; i++)
                    {
                        dataGridView10[1, i].Value = (i + 1).ToString();
                        dataGridView10[5, i].Value = (2 * m_rownum - i).ToString();
                        dataGridView10.Rows[i].Height = 50;
                    }
                    dataGridView10.Columns[1].DefaultCellStyle.BackColor = System.Drawing.Color.Pink;
                    dataGridView10.Columns[5].DefaultCellStyle.BackColor = System.Drawing.Color.Pink;
                    dataGridView10.Columns[3].DefaultCellStyle.BackColor = System.Drawing.Color.Gray;
                    dataGridView10.Columns[2].DefaultCellStyle.BackColor = System.Drawing.Color.LightGray;
                    dataGridView10.Columns[4].DefaultCellStyle.BackColor = System.Drawing.Color.LightGray;
                    dataGridView10.Columns[1].Width = 30;
                    dataGridView10.Columns[5].Width = 30;
                    dataGridView10.Columns[2].Width = 40;
                    dataGridView10.Columns[4].Width = 40;
                    dataGridView10.Columns[3].Width = 100;
                    break;
                case "BGA":
                case "LGA":
                    for (i = 0; i <= m_columnum; i++)
                    {
                        dataGridView10.Columns.Add("column" + i, "");
                        dataGridView10.Columns[i].Width = 50;
                        dataGridView10.Columns[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                    }
                    for (i = 0; i <= m_rownum; i++)
                    {
                        dataGridView10.Rows.Add();
                    }
                    dataGridView10[0, 0].Style.BackColor = System.Drawing.Color.Gray;
                    for (i = 1; i <= m_columnum; i++)
                    {
                        dataGridView10[i, 0].Value = i.ToString();
                        dataGridView10[i, 0].Style.BackColor = System.Drawing.Color.Pink;
                    }
                    for (i = 1; i <= m_rownum; i++)
                    {
                        dataGridView10[0, i].Value = fbga_alph[i - 1];
                        dataGridView10[0, i].Style.BackColor = System.Drawing.Color.Pink;
                        dataGridView10.Rows[i].Height = 50;
                    }
                    dataGridView10.Rows[0].Height = 20;
                    dataGridView10.Columns[0].Width = 30;
                    break;
                case "QFP":
                case "PLCC":
                    // create a circle
                    for (i = 0; i < m_columnum + 6; i++)
                    {
                        dataGridView10.Columns.Add("column" + i.ToString(), "");
                        dataGridView10.Columns[i].Width = 50;
                        dataGridView10.Columns[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                    }

                    for (i = 0; i < m_rownum + 6; i++)
                    {
                        dataGridView10.Rows.Add();
                    }

                    for (i = 4; i < m_rownum + 4; i++)
                    {
                        dataGridView10[1, i - 1].Value = (i - 3).ToString();
                        dataGridView10[m_columnum + 4, i - 1].Value = (2 * m_rownum + m_columnum + 4 - i).ToString();
                        dataGridView10[1, i - 1].Style.BackColor = System.Drawing.Color.Pink;
                        dataGridView10[m_columnum + 4, i - 1].Style.BackColor = System.Drawing.Color.Pink;
                        dataGridView10.Rows[i - 1].Height = 50;
                    }

                    dataGridView10.Columns[2].DefaultCellStyle.BackColor = System.Drawing.Color.LightGray;
                    dataGridView10.Columns[m_columnum + 3].DefaultCellStyle.BackColor = System.Drawing.Color.LightGray;
                    dataGridView10.Rows[2].DefaultCellStyle.BackColor = System.Drawing.Color.LightGray;
                    dataGridView10.Rows[m_rownum + 3].DefaultCellStyle.BackColor = System.Drawing.Color.LightGray;

                    for (i = 0; i < 3; i++)
                    {
                        dataGridView10[m_columnum + 3, i].Style.BackColor = System.Drawing.Color.Gray;
                        dataGridView10[m_columnum + 4, i].Style.BackColor = System.Drawing.Color.Gray;
                        dataGridView10[m_columnum + 5, i].Style.BackColor = System.Drawing.Color.Gray;

                        dataGridView10[0, i].Style.BackColor = System.Drawing.Color.Gray;
                        dataGridView10[1, i].Style.BackColor = System.Drawing.Color.Gray;
                        dataGridView10[2, i].Style.BackColor = System.Drawing.Color.Gray;

                        dataGridView10[i, m_rownum + 3].Style.BackColor = System.Drawing.Color.Gray;
                        dataGridView10[i, m_rownum + 4].Style.BackColor = System.Drawing.Color.Gray;
                        dataGridView10[i, m_rownum + 5].Style.BackColor = System.Drawing.Color.Gray;

                        dataGridView10[m_columnum + 3 + i, m_rownum + 3].Style.BackColor = System.Drawing.Color.Gray;
                        dataGridView10[m_columnum + 3 + i, m_rownum + 4].Style.BackColor = System.Drawing.Color.Gray;
                        dataGridView10[m_columnum + 3 + i, m_rownum + 5].Style.BackColor = System.Drawing.Color.Gray;

                    }
                    dataGridView10.Rows[0].Height = 50;
                    dataGridView10.Rows[1].Height = 30;
                    dataGridView10.Rows[2].Height = 40;
                    dataGridView10.Rows[m_rownum + 3].Height = 40;
                    dataGridView10.Rows[m_rownum + 4].Height = 30;
                    dataGridView10.Rows[m_rownum + 5].Height = 50;

                    for (i = 3; i < m_columnum + 3; i++)
                    {
                        dataGridView10[i, m_rownum + 4].Value = (m_rownum + i - 2).ToString();
                        dataGridView10[i, m_rownum + 4].Style.BackColor = System.Drawing.Color.Pink;
                        dataGridView10[i, 1].Value = (2 * m_rownum + 2 * m_columnum + 3 - i).ToString();
                        dataGridView10[i, 1].Style.BackColor = System.Drawing.Color.Pink;
                        for (j = 3; j < m_rownum + 3; j++)
                        {
                            dataGridView10[i, j].Style.BackColor = System.Drawing.Color.Gray;
                        }
                    }
                    dataGridView10.Columns[0].Width = 50;
                    dataGridView10.Columns[1].Width = 30;
                    dataGridView10.Columns[2].Width = 40;
                    dataGridView10.Columns[m_columnum + 3].Width = 40;
                    dataGridView10.Columns[m_columnum + 4].Width = 30;
                    dataGridView10.Columns[m_columnum + 5].Width = 50;
                    break;
                case "QFN":
                    // create a circle, plus a center point
                    for (i = 0; i < m_columnum + 6; i++)
                    {
                        dataGridView10.Columns.Add("column" + i.ToString(), "");
                        dataGridView10.Columns[i].Width = 50;
                        dataGridView10.Columns[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                    }

                    for (i = 0; i < m_rownum + 6; i++)
                    {
                        dataGridView10.Rows.Add();
                    }

                    for (i = 4; i < m_rownum + 4; i++)
                    {
                        dataGridView10[1, i - 1].Value = (i - 3).ToString();
                        dataGridView10[m_columnum + 4, i - 1].Value = (2 * m_rownum + m_columnum + 4 - i).ToString();
                        dataGridView10[1, i - 1].Style.BackColor = System.Drawing.Color.Pink;
                        dataGridView10[m_columnum + 4, i - 1].Style.BackColor = System.Drawing.Color.Pink;
                        dataGridView10.Rows[i - 1].Height = 50;
                    }

                    dataGridView10.Columns[2].DefaultCellStyle.BackColor = System.Drawing.Color.LightGray;
                    dataGridView10.Columns[m_columnum + 3].DefaultCellStyle.BackColor = System.Drawing.Color.LightGray;
                    dataGridView10.Rows[2].DefaultCellStyle.BackColor = System.Drawing.Color.LightGray;
                    dataGridView10.Rows[m_rownum + 3].DefaultCellStyle.BackColor = System.Drawing.Color.LightGray;

                    for (i = 0; i < 3; i++)
                    {
                        dataGridView10[m_columnum + 3, i].Style.BackColor = System.Drawing.Color.Gray;
                        dataGridView10[m_columnum + 4, i].Style.BackColor = System.Drawing.Color.Gray;
                        dataGridView10[m_columnum + 5, i].Style.BackColor = System.Drawing.Color.Gray;

                        dataGridView10[0, i].Style.BackColor = System.Drawing.Color.Gray;
                        dataGridView10[1, i].Style.BackColor = System.Drawing.Color.Gray;
                        dataGridView10[2, i].Style.BackColor = System.Drawing.Color.Gray;

                        dataGridView10[i, m_rownum + 3].Style.BackColor = System.Drawing.Color.Gray;
                        dataGridView10[i, m_rownum + 4].Style.BackColor = System.Drawing.Color.Gray;
                        dataGridView10[i, m_rownum + 5].Style.BackColor = System.Drawing.Color.Gray;

                        dataGridView10[m_columnum + 3 + i, m_rownum + 3].Style.BackColor = System.Drawing.Color.Gray;
                        dataGridView10[m_columnum + 3 + i, m_rownum + 4].Style.BackColor = System.Drawing.Color.Gray;
                        dataGridView10[m_columnum + 3 + i, m_rownum + 5].Style.BackColor = System.Drawing.Color.Gray;

                    }
                    dataGridView10.Rows[0].Height = 50;
                    dataGridView10.Rows[1].Height = 30;
                    dataGridView10.Rows[2].Height = 40;
                    dataGridView10.Rows[m_rownum + 3].Height = 40;
                    dataGridView10.Rows[m_rownum + 4].Height = 30;
                    dataGridView10.Rows[m_rownum + 5].Height = 50;

                    for (i = 3; i < m_columnum + 3; i++)
                    {
                        dataGridView10[i, m_rownum + 4].Value = (m_rownum + i - 2).ToString();
                        dataGridView10[i, m_rownum + 4].Style.BackColor = System.Drawing.Color.Pink;
                        dataGridView10[i, 1].Value = (2 * m_rownum + 2 * m_columnum + 3 - i).ToString();
                        dataGridView10[i, 1].Style.BackColor = System.Drawing.Color.Pink;
                        for (j = 3; j < m_rownum + 3; j++)
                        {
                            dataGridView10[i, j].Style.BackColor = System.Drawing.Color.Gray;
                        }
                    }
                    dataGridView10.Columns[0].Width = 50;
                    dataGridView10.Columns[1].Width = 30;
                    dataGridView10.Columns[2].Width = 40;
                    dataGridView10.Columns[m_columnum + 3].Width = 40;
                    dataGridView10.Columns[m_columnum + 4].Width = 30;
                    dataGridView10.Columns[m_columnum + 5].Width = 50;

                    dataGridView10[3 + m_columnum / 2, 3 + m_rownum / 2].Style.BackColor = System.Drawing.Color.White;
                    break;
            }
        }

        // view detail, load pinmap, noteimage, adapterlist three tabs
        private void button4_Click(object sender, EventArgs e)
        {
            if (m_login == false)
            {
                MessageBox.Show("Please log in first!", "Warning");
                return;
            }
            if (dataGridView9.RowCount < 1)
            {
                return;
            }

            m_adptrid = int.Parse(dataGridView9[0, dataGridView9.CurrentCell.RowIndex].Value.ToString());
            AccessDataBase adb = new AccessDataBase();
            AdapterListTableElement alte = new AdapterListTableElement();
            alte = adb.LoadAdapterListTable(m_adptrid);
            m_pinmapid = alte.PinMapId; // get the pinmapid
            textBox4.Text = m_pinmapid.ToString();
            PinMapListElement pmle = new PinMapListElement();
            pmle = adb.LoadPinMapListTable(m_pinmapid);
            m_pckname = pmle.PackageName;
            comboBox1.Text = m_pckname;
            m_rownum = pmle.RowNum;
            numericUpDown1.Value = m_rownum;
            m_columnum = pmle.ColumnNum;
            numericUpDown2.Value = m_columnum;
            //m_totalp = 0;

            // 1. create map tab
            m_OperationMode = 0;
            createPinMapToolStripMenuItem_Click(sender, e);
            m_OperationMode = 1;

            //m_labelist = filefp.LabelList;
            m_totalp = pmle.TotalPins;
            //m_listsize = filefp.ListSize;
            textBox3.Text = m_totalp.ToString();

            dataGridView2.ColumnCount = 3;
            dataGridView2.RowCount = m_listsize;
            PinOutListElement pole = new PinOutListElement();
            string loc;
            for (int i = 0; i < m_listsize; i++)
            {
                loc = dataGridView2[0, i].Value.ToString();
                pole = adb.LoadPinOutListTable(m_pinmapid, loc);
                if (null != pole)
                {
                    m_labelist[i] = pole.Label;
                    m_devpinlist[i] = pole.DevicePin;
                    dataGridView2[1, i].Value = m_labelist[i];
                    dataGridView2[2, i].Value = m_devpinlist[i];
                }
            }
            AlignPinMap();

            // 2. create noteimage tab
            // 2.1 get notelist using pinmapid
            string[] notelist = new string[10];
            int no_note = 0;
            no_note = adb.QueryNote4PinMapId(ref notelist, m_pinmapid);
            dataGridView4.RowCount = 0;
            if (no_note > 0)
            {
                for (int j = 0; j < no_note; j++)
                {
                    dataGridView4.Rows.Add((j + 1).ToString());
                    dataGridView4[1, j].Value = notelist[j];
                    dataGridView4.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
                }
            }
            // 2.2 get imagelist using pinmapid
            int no_image = 0;
            ImageListElement[] imagelist = new ImageListElement[10];
            no_image = adb.SearchImageListTable(m_pinmapid, ref imagelist);
            dataGridView5.RowCount = 0;
            if (no_image > 0)
            {
                for (int k = 0; k < no_image; k++)
                {
                    dataGridView5.Rows.Add((k + 1).ToString());
                    dataGridView5.Rows[k].Height = 200;
                    MemoryStream buf = new MemoryStream((byte[])imagelist[k].ImagesByte);
                    dataGridView5[1, k].Value = Image.FromStream(buf, true);
                }
            }

            // 3. create adapter tab
            int no_adapter = 0;
            AdapterListTableElement[] adapterlist = new AdapterListTableElement[20];
            no_adapter = adb.QueryAdapter4PinMapId(ref adapterlist, m_pinmapid);
            HWParamTableElement hwpte = new HWParamTableElement();
            dataGridView6.RowCount = 0;
            dataGridView7.RowCount = 0;
            dataGridView8.RowCount = 0;
            dataGridView7.ColumnCount = 1;
            dataGridView8.ColumnCount = 1;
            if (no_adapter > 0)
            {
                for (int l = 0; l < no_adapter; l++)
                {
                    // 3.1 get adapter list
                    dataGridView6.Rows.Add(adapterlist[l].AdapterId, adapterlist[l].AdapterName, adapterlist[l].SocketId);

                    // 3.2 get hwparam list
                    // add column to the datagridview7
                    if (dataGridView7.ColumnCount == 1)
                    {
                        //DataGridViewTextBoxColumn dgvtbc = new DataGridViewTextBoxColumn();
                        //dgvtbc.HeaderText = "";
                        //dataGridView7.Columns.Add(dgvtbc);
                        // add the row header first
                        dataGridView7.Rows.Add("<HWParams>");
                        ////dataGridView7.Rows.Add("HWParamId");
                        dataGridView7.Rows.Add("PackageInfo");
                        dataGridView7.Rows.Add("SocketNum");
                        dataGridView7.Rows.Add("PinOneOri");
                        dataGridView7.Rows.Add("BodySize");
                        dataGridView7.Rows.Add("Width");
                        dataGridView7.Rows.Add("Pitch");
                        dataGridView7.Rows.Add("BallDiameter");
                        dataGridView7.Rows.Add("BallHeight");
                        dataGridView7.Rows.Add("PkgHeight");
                        //dataGridView7[0, 0].Style.BackColor = System.Drawing.Color.Blue;
                        dataGridView7.Columns[0].ReadOnly = true;
                        dataGridView7.Rows[0].ReadOnly = true;
                        for (int i = 0; i < 10; i++)
                        {
                            dataGridView7.Rows[i].Height = 42;
                            dataGridView7[0, i].Style.BackColor = System.Drawing.Color.Pink;
                        }
                    }
                    int temp = dataGridView7.ColumnCount;
                    DataGridViewTextBoxColumn dgvtbc1 = new DataGridViewTextBoxColumn();
                    dgvtbc1.HeaderText = "AdapterId";
                    dgvtbc1.Width = 60;
                    dataGridView7.Columns.Add(dgvtbc1);
                    dataGridView7[temp, 0].Value = adapterlist[l].AdapterId;
                    dataGridView7[temp, 1].Value = adapterlist[l].PackageInfo;
                    dataGridView7[temp, 2].Value = adapterlist[l].SocketNum;
                    dataGridView7[temp, 3].Value = adapterlist[l].PinOneOri;
                    hwpte = adb.LoadSocket4Id(adapterlist[l].SocketId);
                    dataGridView7[temp, 4].Value = hwpte.BodySize;
                    dataGridView7[temp, 5].Value = hwpte.Width;
                    dataGridView7[temp, 6].Value = hwpte.Pitch;
                    dataGridView7[temp, 7].Value = hwpte.BallDiameter;
                    dataGridView7[temp, 8].Value = hwpte.BallHeight;
                    dataGridView7[temp, 9].Value = hwpte.PkgHeight;
                    dataGridView7[temp, 0].Style.BackColor = System.Drawing.Color.Cyan;
                    dataGridView7.Columns[temp].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

                    // add column to the datagridview8
                    string[] loclist = new string[m_listsize];
                    int[] oplist = new int[m_listsize];
                    int no_option = 0;
                    no_option = adb.QueryOption4AdapterId(ref loclist, ref oplist, adapterlist[l].AdapterId);
                    if (dataGridView8.ColumnCount == 1)
                    {
                        dataGridView8.Rows.Add("<Loc>");
                        for (int k = 0; k < m_listsize; k++)
                        {
                            dataGridView8.Rows.Add(m_posilist[k]);
                        }
                        dataGridView8.Columns[0].ReadOnly = true;
                        dataGridView8.Rows[0].ReadOnly = true;
                        //dataGridView8[0, 0].Style.BackColor = System.Drawing.Color.Blue;
                        dataGridView8.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                        for (int m = 0; m <= m_listsize; m++)
                        {
                            dataGridView8.Rows[m].Height = 30;
                            dataGridView8[0, m].Style.BackColor = System.Drawing.Color.Pink;
                        }
                    }
                    temp = dataGridView8.ColumnCount;
                    DataGridViewTextBoxColumn dgvtbc2 = new DataGridViewTextBoxColumn();
                    dgvtbc2.HeaderText = "AdptrId";
                    dgvtbc2.Width = 60;
                    dataGridView8.Columns.Add(dgvtbc2);
                    dataGridView8.Columns[temp].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                    dataGridView8[temp, 0].Value = adapterlist[l].AdapterId;
                    for (int m = 0; m < m_listsize; m++)
                    {
                        //dataGridView8[temp, m + 1].Value = 1;
                        for (int n = 0; n < no_option; n++)
                        {
                            if (loclist[n] == m_posilist[m])
                            {
                                dataGridView8[temp, m + 1].Value = oplist[n];
                                n = no_option;
                            }
                        }
                    }
                    dataGridView8[temp, 0].Style.BackColor = System.Drawing.Color.Cyan;
                }
            }
        }

        private void textBox1_TextChanged_1(object sender, EventArgs e)
        {
            if (textBox1.Text == null ||
                textBox1.Text == "")
            {
                textBox1.Text = "0";
            }
        }

        private void groupBox9_Enter(object sender, EventArgs e)
        {

        }

        private void comboBox5_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox5.Text == null ||
                comboBox5.Text == "")
            {
                comboBox5.Text = "Any";
            }
        }

        private void comboBox5_TextChanged(object sender, EventArgs e)
        {
            if (comboBox5.Text == null ||
                comboBox5.Text == "")
            {
                comboBox5.Text = "Any";
            }
        }

        private void comboBox6_TextChanged(object sender, EventArgs e)
        {
            if (comboBox6.Text == null ||
                comboBox6.Text == "" ||
                (!ValidateString2Number(comboBox6.Text)))
            {
                comboBox6.Text = "Any";
            }
        }

        // Valideate String as Number
        public bool ValidateString2Number(string str)
        {
            bool ret = true;
            char[] arr_ch = str.ToCharArray();
            int length = str.Length;
            for (int i = 0; i < length; i++)
            {
                if (arr_ch[i] == '.' ||
                    ('0' <= arr_ch[i] && '9' >= arr_ch[i]))
                {
                    continue;
                }
                else
                {
                    ret = false;
                    break;
                }
            }

            return ret;
        }

        private void comboBox7_TextChanged(object sender, EventArgs e)
        {
            if (comboBox7.Text == null ||
                comboBox7.Text == "" ||
                (!ValidateString2Number(comboBox7.Text)))
            {
                comboBox7.Text = "Any";
            }
        }

        private void comboBox8_TextChanged(object sender, EventArgs e)
        {
            if (comboBox8.Text == null ||
                comboBox8.Text == "" ||
                (!ValidateString2Number(comboBox8.Text)))
            {
                comboBox8.Text = "Any";
            }
        }

        private void comboBox9_TextChanged(object sender, EventArgs e)
        {
            if (comboBox9.Text == null ||
                comboBox9.Text == "" ||
                (!ValidateString2Number(comboBox9.Text)))
            {
                comboBox9.Text = "Any";
            }
        }

        private void comboBox10_TextChanged(object sender, EventArgs e)
        {
            if (comboBox10.Text == null ||
                comboBox10.Text == "" ||
                (!ValidateString2Number(comboBox10.Text)))
            {
                comboBox10.Text = "Any";
            }
        }

        private void comboBox11_TextChanged(object sender, EventArgs e)
        {
            if (comboBox11.Text == null ||
                comboBox11.Text == "" ||
                (!ValidateString2Number(comboBox11.Text)))
            {
                comboBox11.Text = "Any";
            }
        }

        private void comboBox12_TextChanged(object sender, EventArgs e)
        {
            if (comboBox12.Text == null ||
                comboBox12.Text == "" ||
                (!ValidateString2Number(comboBox12.Text)))
            {
                comboBox12.Text = "Any";
            }
        }

        private void comboBox13_TextChanged(object sender, EventArgs e)
        {
            if (comboBox13.Text == null ||
                comboBox13.Text == "" ||
                (!ValidateString2Number(comboBox13.Text)))
            {
                comboBox13.Text = "Any";
            }
        }

        private void button8_Click(object sender, EventArgs e)
        {
            if (m_login == false)
            {
                MessageBox.Show("Please log in first!", "Warning");
                return;
            }
            if (m_OperationMode == 1)
            {
                // if in Search Mode, return;
                MessageBox.Show("You can only unlock records under Define Mode.", "Warning");
                return;
            }
            m_lock = false;
            dataGridView2.ReadOnly = false;
            dataGridView3.ReadOnly = false;
            dataGridView4.ReadOnly = false;
            dataGridView5.ReadOnly = false;
            dataGridView6.ReadOnly = false;
            dataGridView7.ReadOnly = false;
            dataGridView8.ReadOnly = false;

            textBox4.ReadOnly = false;
            numericUpDown1.Enabled = true;
            numericUpDown2.Enabled = true;
            comboBox1.Enabled = true;
            textBox3.ReadOnly = false;
        }

        private void groupBox10_Enter(object sender, EventArgs e)
        {

        }

        // change password
        private void changePWDToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (m_login == false)
            {
                MessageBox.Show("Please log in first!", "Warning");
                return;
            }

            ChangePasswordForm cpf = new ChangePasswordForm();
            if (cpf.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            // 1. check old password
            AccessDataBase adb = new AccessDataBase();
            UserListTableElement ulte = new UserListTableElement();
            ulte = adb.LoadUserListTableElement(m_user);
            if (ulte.Password == cpf.OldPassword)
            {
                // change to the new password
                ulte.Password = cpf.NewPassword1;
                adb.UpdateRecUserListTable(ulte);
                MessageBox.Show("Change password succeed!", "Note");
                return;
            }
            else
            { 
                // give warning the old password is incorrect
                MessageBox.Show("Password is incorrect! Change password failed!", "Warning");
                return;
            }
        }

        private void logInToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LogInForm lif = new LogInForm();
            if (lif.ShowDialog() != DialogResult.OK)
                return;
            m_login = true;
            m_privilege = lif.ULTE.Privilege;
            m_user = lif.ULTE.User;
            textBox13.Text = m_user;
            switch (m_privilege)
            { 
                case 1:
                    // for admin
                    m_OperationMode = 0;
                    label1.Text = "Define Mode";
                    tabControl1.SelectedIndex = 0;
                    break;
                case 2:
                    // for engineer
                    m_OperationMode = 1;
                    label1.Text = "Search Mode";
                    tabControl1.SelectedIndex = 3;
                    break;
                case 0:
                    // for general user
                    m_OperationMode = 1;
                    label1.Text = "Search Mode";
                    tabControl1.SelectedIndex = 3;
                    break;
                default:
                    // do nothing
                    break;
            }

            return;
        }

        private void logOutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            m_login = false;
            textBox13.Text = "";
            m_privilege = -1;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            //LogInForm lif = new LogInForm();
            //if (lif.ShowDialog() != DialogResult.OK)
            //    return;
            //m_login = true;
            //m_privilege = lif.ULTE.Privilege;
            //m_user = lif.ULTE.User;
            //textBox13.Text = m_user;
        }

        private void button14_Click_1(object sender, EventArgs e)
        {
            // view all information about the adapter.
            if (m_login == false)
            {
                MessageBox.Show("Please log in first!", "Warning");
                return;
            }
            if (dataGridView9.RowCount < 1)
            {
                return;
            }
            statusStrip.Text = "Loading ...";
            button4_Click(sender, e);
            dataGridView2.ReadOnly = true;
            dataGridView3.ReadOnly = true;
            dataGridView4.ReadOnly = true;
            dataGridView5.ReadOnly = true;
            dataGridView6.ReadOnly = true;
            dataGridView7.ReadOnly = true;
            dataGridView8.ReadOnly = true;
            textBox3.ReadOnly = true;
            textBox4.ReadOnly = true;
            numericUpDown1.Enabled = false;
            numericUpDown2.Enabled = false;
            comboBox1.Enabled = false;

            if (dataGridView3.RowCount < 1 ||
                dataGridView3.ColumnCount < 1)
                return;

            Image temp = Image.FromFile(@"demo.jpg");
            GetResultIntoImage(ref temp, true);//, dataGridView3);
            PrintPrevForm ppf = new PrintPrevForm();
            ppf.pictureBox1.Image = temp;
            ppf.Show();
            ppf.button1.Enabled = false;
            ppf.button2.Enabled = false;
            ppf.button1.Visible = false;
            ppf.button2.Visible = false;
            statusStrip.Text = "Ready";
        }

        private void readMeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process cmd = new Process();
            cmd.StartInfo.FileName = "cmd";
            cmd.StartInfo.RedirectStandardOutput = true;
            cmd.StartInfo.RedirectStandardInput = true;
            cmd.StartInfo.UseShellExecute = false;
            cmd.StartInfo.CreateNoWindow = false;

            cmd.Start();

            // remove some files
            string str;
            str = Environment.CurrentDirectory;
            //MessageBox.Show(str);
            //cmd.StandardInput.WriteLine("D:");
            //cmd.StandardInput.WriteLine("cd \\");
            //cmd.StandardInput.WriteLine("cd \\AdapterTool_Beta\\");
            //cmd.StandardInput.WriteLine("cd " + str);
            if (m_privilege > 0)
            {
                //str += "\start Readme_Engineer.pdf";
                //cmd.StandardInput.WriteLine(@str);
                cmd.StandardInput.WriteLine(str + "\\Readme_Engineer.pdf");
            }
            else
            {
                cmd.StandardInput.WriteLine(str + "\\Readme_User.pdf");
            }

            // install new algorithm packages
            cmd.StandardInput.WriteLine("exit");
            cmd.Close();
        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {
            //if (m_lock)
            //{
            //    MessageBox.Show("The record is locked.", "Note");
            //    return;
            //}
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Return)
            {
                button3_Click(sender, e);
            }
        }
    }
}
